This file is indexed.

/usr/lib/python3/dist-packages/twisted/test/test_tcp.py is in python3-twisted-experimental 13.2.0-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for implementations of L{IReactorTCP}.
"""

from __future__ import division, absolute_import

import socket, random, errno
from functools import wraps

from zope.interface import implementer

from twisted.trial import unittest

from twisted.python.log import msg
from twisted.internet import protocol, reactor, defer, interfaces
from twisted.internet import error
from twisted.internet.address import IPv4Address
from twisted.internet.interfaces import IHalfCloseableProtocol, IPullProducer
from twisted.protocols import policies
from twisted.test.proto_helpers import AccumulatingProtocol


def loopUntil(predicate, interval=0):
    """
    Poor excuse for an event notification helper.  This polls a condition and
    calls back a Deferred when it is seen to be true.

    Do not use this function.
    """
    from twisted.internet import task
    d = defer.Deferred()
    def check():
        res = predicate()
        if res:
            d.callback(res)
    call = task.LoopingCall(check)
    def stop(result):
        call.stop()
        return result
    d.addCallback(stop)
    d2 = call.start(interval)
    d2.addErrback(d.errback)
    return d



class ClosingProtocol(protocol.Protocol):

    def connectionMade(self):
        msg("ClosingProtocol.connectionMade")
        self.transport.loseConnection()

    def connectionLost(self, reason):
        msg("ClosingProtocol.connectionLost")
        reason.trap(error.ConnectionDone)



class ClosingFactory(protocol.ServerFactory):
    """
    Factory that closes port immediately.
    """

    _cleanerUpper = None

    def buildProtocol(self, conn):
        self._cleanerUpper = self.port.stopListening()
        return ClosingProtocol()


    def cleanUp(self):
        """
        Clean-up for tests to wait for the port to stop listening.
        """
        if self._cleanerUpper is None:
            return self.port.stopListening()
        return self._cleanerUpper



class MyProtocolFactoryMixin(object):
    """
    Mixin for factories which create L{AccumulatingProtocol} instances.

    @type protocolFactory: no-argument callable
    @ivar protocolFactory: Factory for protocols - takes the place of the
        typical C{protocol} attribute of factories (but that name is used by
        this class for something else).

    @type protocolConnectionMade: L{NoneType} or L{defer.Deferred}
    @ivar protocolConnectionMade: When an instance of L{AccumulatingProtocol}
        is connected, if this is not C{None}, the L{Deferred} will be called
        back with the protocol instance and the attribute set to C{None}.

    @type protocolConnectionLost: L{NoneType} or L{defer.Deferred}
    @ivar protocolConnectionLost: When an instance of L{AccumulatingProtocol}
        is created, this will be set as its C{closedDeferred} attribute and
        then this attribute will be set to C{None} so the L{defer.Deferred} is
        not used by more than one protocol.

    @ivar protocol: The most recently created L{AccumulatingProtocol} instance
        which was returned from C{buildProtocol}.

    @type called: C{int}
    @ivar called: A counter which is incremented each time C{buildProtocol}
        is called.

    @ivar peerAddresses: A C{list} of the addresses passed to C{buildProtocol}.
    """
    protocolFactory = AccumulatingProtocol

    protocolConnectionMade = None
    protocolConnectionLost = None
    protocol = None
    called = 0

    def __init__(self):
        self.peerAddresses = []


    def buildProtocol(self, addr):
        """
        Create a L{AccumulatingProtocol} and set it up to be able to perform
        callbacks.
        """
        self.peerAddresses.append(addr)
        self.called += 1
        p = self.protocolFactory()
        p.factory = self
        p.closedDeferred = self.protocolConnectionLost
        self.protocolConnectionLost = None
        self.protocol = p
        return p



class MyServerFactory(MyProtocolFactoryMixin, protocol.ServerFactory):
    """
    Server factory which creates L{AccumulatingProtocol} instances.
    """



class MyClientFactory(MyProtocolFactoryMixin, protocol.ClientFactory):
    """
    Client factory which creates L{AccumulatingProtocol} instances.
    """
    failed = 0
    stopped = 0

    def __init__(self):
        MyProtocolFactoryMixin.__init__(self)
        self.deferred = defer.Deferred()
        self.failDeferred = defer.Deferred()

    def clientConnectionFailed(self, connector, reason):
        self.failed = 1
        self.reason = reason
        self.failDeferred.callback(None)

    def clientConnectionLost(self, connector, reason):
        self.lostReason = reason
        self.deferred.callback(None)

    def stopFactory(self):
        self.stopped = 1



class ListeningTestCase(unittest.TestCase):

    def test_listen(self):
        """
        L{IReactorTCP.listenTCP} returns an object which provides
        L{IListeningPort}.
        """
        f = MyServerFactory()
        p1 = reactor.listenTCP(0, f, interface="127.0.0.1")
        self.addCleanup(p1.stopListening)
        self.failUnless(interfaces.IListeningPort.providedBy(p1))


    def testStopListening(self):
        """
        The L{IListeningPort} returned by L{IReactorTCP.listenTCP} can be
        stopped with its C{stopListening} method.  After the L{Deferred} it
        (optionally) returns has been called back, the port number can be bound
        to a new server.
        """
        f = MyServerFactory()
        port = reactor.listenTCP(0, f, interface="127.0.0.1")
        n = port.getHost().port

        def cbStopListening(ignored):
            # Make sure we can rebind the port right away
            port = reactor.listenTCP(n, f, interface="127.0.0.1")
            return port.stopListening()

        d = defer.maybeDeferred(port.stopListening)
        d.addCallback(cbStopListening)
        return d


    def testNumberedInterface(self):
        f = MyServerFactory()
        # listen only on the loopback interface
        p1 = reactor.listenTCP(0, f, interface='127.0.0.1')
        return p1.stopListening()

    def testPortRepr(self):
        f = MyServerFactory()
        p = reactor.listenTCP(0, f)
        portNo = str(p.getHost().port)
        self.failIf(repr(p).find(portNo) == -1)
        def stoppedListening(ign):
            self.failIf(repr(p).find(portNo) != -1)
        d = defer.maybeDeferred(p.stopListening)
        return d.addCallback(stoppedListening)


    def test_serverRepr(self):
        """
        Check that the repr string of the server transport get the good port
        number if the server listens on 0.
        """
        server = MyServerFactory()
        serverConnMade = server.protocolConnectionMade = defer.Deferred()
        port = reactor.listenTCP(0, server)
        self.addCleanup(port.stopListening)

        client = MyClientFactory()
        clientConnMade = client.protocolConnectionMade = defer.Deferred()
        connector = reactor.connectTCP("127.0.0.1",
                                       port.getHost().port, client)
        self.addCleanup(connector.disconnect)
        def check(result):
            serverProto, clientProto = result
            portNumber = port.getHost().port
            self.assertEqual(
                repr(serverProto.transport),
                "<AccumulatingProtocol #0 on %s>" % (portNumber,))
            serverProto.transport.loseConnection()
            clientProto.transport.loseConnection()
        return defer.gatherResults([serverConnMade, clientConnMade]
            ).addCallback(check)


    def test_restartListening(self):
        """
        Stop and then try to restart a L{tcp.Port}: after a restart, the
        server should be able to handle client connections.
        """
        serverFactory = MyServerFactory()
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        self.addCleanup(port.stopListening)

        def cbStopListening(ignored):
            port.startListening()

            client = MyClientFactory()
            serverFactory.protocolConnectionMade = defer.Deferred()
            client.protocolConnectionMade = defer.Deferred()
            connector = reactor.connectTCP("127.0.0.1",
                                           port.getHost().port, client)
            self.addCleanup(connector.disconnect)
            return defer.gatherResults([serverFactory.protocolConnectionMade,
                                        client.protocolConnectionMade]
                ).addCallback(close)

        def close(result):
            serverProto, clientProto = result
            clientProto.transport.loseConnection()
            serverProto.transport.loseConnection()

        d = defer.maybeDeferred(port.stopListening)
        d.addCallback(cbStopListening)
        return d


    def test_exceptInStop(self):
        """
        If the server factory raises an exception in C{stopFactory}, the
        deferred returned by L{tcp.Port.stopListening} should fail with the
        corresponding error.
        """
        serverFactory = MyServerFactory()
        def raiseException():
            raise RuntimeError("An error")
        serverFactory.stopFactory = raiseException
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")

        return self.assertFailure(port.stopListening(), RuntimeError)


    def test_restartAfterExcept(self):
        """
        Even if the server factory raise an exception in C{stopFactory}, the
        corresponding C{tcp.Port} instance should be in a sane state and can
        be restarted.
        """
        serverFactory = MyServerFactory()
        def raiseException():
            raise RuntimeError("An error")
        serverFactory.stopFactory = raiseException
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        self.addCleanup(port.stopListening)

        def cbStopListening(ignored):
            del serverFactory.stopFactory
            port.startListening()

            client = MyClientFactory()
            serverFactory.protocolConnectionMade = defer.Deferred()
            client.protocolConnectionMade = defer.Deferred()
            connector = reactor.connectTCP("127.0.0.1",
                                           port.getHost().port, client)
            self.addCleanup(connector.disconnect)
            return defer.gatherResults([serverFactory.protocolConnectionMade,
                                        client.protocolConnectionMade]
                ).addCallback(close)

        def close(result):
            serverProto, clientProto = result
            clientProto.transport.loseConnection()
            serverProto.transport.loseConnection()

        return self.assertFailure(port.stopListening(), RuntimeError
            ).addCallback(cbStopListening)


    def test_directConnectionLostCall(self):
        """
        If C{connectionLost} is called directly on a port object, it succeeds
        (and doesn't expect the presence of a C{deferred} attribute).

        C{connectionLost} is called by L{reactor.disconnectAll} at shutdown.
        """
        serverFactory = MyServerFactory()
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        portNumber = port.getHost().port
        port.connectionLost(None)

        client = MyClientFactory()
        serverFactory.protocolConnectionMade = defer.Deferred()
        client.protocolConnectionMade = defer.Deferred()
        reactor.connectTCP("127.0.0.1", portNumber, client)
        def check(ign):
            client.reason.trap(error.ConnectionRefusedError)
        return client.failDeferred.addCallback(check)


    def test_exceptInConnectionLostCall(self):
        """
        If C{connectionLost} is called directory on a port object and that the
        server factory raises an exception in C{stopFactory}, the exception is
        passed through to the caller.

        C{connectionLost} is called by L{reactor.disconnectAll} at shutdown.
        """
        serverFactory = MyServerFactory()
        def raiseException():
            raise RuntimeError("An error")
        serverFactory.stopFactory = raiseException
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        self.assertRaises(RuntimeError, port.connectionLost, None)



def callWithSpew(f):
    from twisted.python.util import spewerWithLinenums as spewer
    import sys
    sys.settrace(spewer)
    try:
        f()
    finally:
        sys.settrace(None)

class LoopbackTestCase(unittest.TestCase):
    """
    Test loopback connections.
    """
    def test_closePortInProtocolFactory(self):
        """
        A port created with L{IReactorTCP.listenTCP} can be connected to with
        L{IReactorTCP.connectTCP}.
        """
        f = ClosingFactory()
        port = reactor.listenTCP(0, f, interface="127.0.0.1")
        f.port = port
        self.addCleanup(f.cleanUp)
        portNumber = port.getHost().port
        clientF = MyClientFactory()
        reactor.connectTCP("127.0.0.1", portNumber, clientF)
        def check(x):
            self.assertTrue(clientF.protocol.made)
            self.assertTrue(port.disconnected)
            clientF.lostReason.trap(error.ConnectionDone)
        return clientF.deferred.addCallback(check)

    def _trapCnxDone(self, obj):
        getattr(obj, 'trap', lambda x: None)(error.ConnectionDone)


    def _connectedClientAndServerTest(self, callback):
        """
        Invoke the given callback with a client protocol and a server protocol
        which have been connected to each other.
        """
        serverFactory = MyServerFactory()
        serverConnMade = defer.Deferred()
        serverFactory.protocolConnectionMade = serverConnMade
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        self.addCleanup(port.stopListening)

        portNumber = port.getHost().port
        clientF = MyClientFactory()
        clientConnMade = defer.Deferred()
        clientF.protocolConnectionMade = clientConnMade
        reactor.connectTCP("127.0.0.1", portNumber, clientF)

        connsMade = defer.gatherResults([serverConnMade, clientConnMade])
        def connected(result):
            serverProtocol, clientProtocol = result
            callback(serverProtocol, clientProtocol)
            serverProtocol.transport.loseConnection()
            clientProtocol.transport.loseConnection()
        connsMade.addCallback(connected)
        return connsMade


    def test_tcpNoDelay(self):
        """
        The transport of a protocol connected with L{IReactorTCP.connectTCP} or
        L{IReactor.TCP.listenTCP} can have its I{TCP_NODELAY} state inspected
        and manipulated with L{ITCPTransport.getTcpNoDelay} and
        L{ITCPTransport.setTcpNoDelay}.
        """
        def check(serverProtocol, clientProtocol):
            for p in [serverProtocol, clientProtocol]:
                transport = p.transport
                self.assertEqual(transport.getTcpNoDelay(), 0)
                transport.setTcpNoDelay(1)
                self.assertEqual(transport.getTcpNoDelay(), 1)
                transport.setTcpNoDelay(0)
                self.assertEqual(transport.getTcpNoDelay(), 0)
        return self._connectedClientAndServerTest(check)


    def test_tcpKeepAlive(self):
        """
        The transport of a protocol connected with L{IReactorTCP.connectTCP} or
        L{IReactor.TCP.listenTCP} can have its I{SO_KEEPALIVE} state inspected
        and manipulated with L{ITCPTransport.getTcpKeepAlive} and
        L{ITCPTransport.setTcpKeepAlive}.
        """
        def check(serverProtocol, clientProtocol):
            for p in [serverProtocol, clientProtocol]:
                transport = p.transport
                self.assertEqual(transport.getTcpKeepAlive(), 0)
                transport.setTcpKeepAlive(1)
                self.assertEqual(transport.getTcpKeepAlive(), 1)
                transport.setTcpKeepAlive(0)
                self.assertEqual(transport.getTcpKeepAlive(), 0)
        return self._connectedClientAndServerTest(check)


    def testFailing(self):
        clientF = MyClientFactory()
        # XXX we assume no one is listening on TCP port 69
        reactor.connectTCP("127.0.0.1", 69, clientF, timeout=5)
        def check(ignored):
            clientF.reason.trap(error.ConnectionRefusedError)
        return clientF.failDeferred.addCallback(check)


    def test_connectionRefusedErrorNumber(self):
        """
        Assert that the error number of the ConnectionRefusedError is
        ECONNREFUSED, and not some other socket related error.
        """

        # Bind a number of ports in the operating system.  We will attempt
        # to connect to these in turn immediately after closing them, in the
        # hopes that no one else has bound them in the mean time.  Any
        # connection which succeeds is ignored and causes us to move on to
        # the next port.  As soon as a connection attempt fails, we move on
        # to making an assertion about how it failed.  If they all succeed,
        # the test will fail.

        # It would be nice to have a simpler, reliable way to cause a
        # connection failure from the platform.
        #
        # On Linux (2.6.15), connecting to port 0 always fails.  FreeBSD
        # (5.4) rejects the connection attempt with EADDRNOTAVAIL.
        #
        # On FreeBSD (5.4), listening on a port and then repeatedly
        # connecting to it without ever accepting any connections eventually
        # leads to an ECONNREFUSED.  On Linux (2.6.15), a seemingly
        # unbounded number of connections succeed.

        serverSockets = []
        for i in range(10):
            serverSocket = socket.socket()
            serverSocket.bind(('127.0.0.1', 0))
            serverSocket.listen(1)
            serverSockets.append(serverSocket)
        random.shuffle(serverSockets)

        clientCreator = protocol.ClientCreator(reactor, protocol.Protocol)

        def tryConnectFailure():
            def connected(proto):
                """
                Darn.  Kill it and try again, if there are any tries left.
                """
                proto.transport.loseConnection()
                if serverSockets:
                    return tryConnectFailure()
                self.fail("Could not fail to connect - could not test errno for that case.")

            serverSocket = serverSockets.pop()
            serverHost, serverPort = serverSocket.getsockname()
            serverSocket.close()

            connectDeferred = clientCreator.connectTCP(serverHost, serverPort)
            connectDeferred.addCallback(connected)
            return connectDeferred

        refusedDeferred = tryConnectFailure()
        self.assertFailure(refusedDeferred, error.ConnectionRefusedError)
        def connRefused(exc):
            self.assertEqual(exc.osError, errno.ECONNREFUSED)
        refusedDeferred.addCallback(connRefused)
        def cleanup(passthrough):
            while serverSockets:
                serverSockets.pop().close()
            return passthrough
        refusedDeferred.addBoth(cleanup)
        return refusedDeferred


    def test_connectByServiceFail(self):
        """
        Connecting to a named service which does not exist raises
        L{error.ServiceNameUnknownError}.
        """
        self.assertRaises(
            error.ServiceNameUnknownError,
            reactor.connectTCP,
            "127.0.0.1", "thisbetternotexist", MyClientFactory())


    def test_connectByService(self):
        """
        L{IReactorTCP.connectTCP} accepts the name of a service instead of a
        port number and connects to the port number associated with that
        service, as defined by L{socket.getservbyname}.
        """
        serverFactory = MyServerFactory()
        serverConnMade = defer.Deferred()
        serverFactory.protocolConnectionMade = serverConnMade
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        self.addCleanup(port.stopListening)
        portNumber = port.getHost().port
        clientFactory = MyClientFactory()
        clientConnMade = defer.Deferred()
        clientFactory.protocolConnectionMade = clientConnMade

        def fakeGetServicePortByName(serviceName, protocolName):
            if serviceName == 'http' and protocolName == 'tcp':
                return portNumber
            return 10
        self.patch(socket, 'getservbyname', fakeGetServicePortByName)

        reactor.connectTCP('127.0.0.1', 'http', clientFactory)

        connMade = defer.gatherResults([serverConnMade, clientConnMade])
        def connected(result):
            serverProtocol, clientProtocol = result
            self.assertTrue(
                serverFactory.called,
                "Server factory was not called upon to build a protocol.")
            serverProtocol.transport.loseConnection()
            clientProtocol.transport.loseConnection()
        connMade.addCallback(connected)
        return connMade


class StartStopFactory(protocol.Factory):

    started = 0
    stopped = 0

    def startFactory(self):
        if self.started or self.stopped:
            raise RuntimeError
        self.started = 1

    def stopFactory(self):
        if not self.started or self.stopped:
            raise RuntimeError
        self.stopped = 1


class ClientStartStopFactory(MyClientFactory):

    started = 0
    stopped = 0

    def __init__(self, *a, **kw):
        MyClientFactory.__init__(self, *a, **kw)
        self.whenStopped = defer.Deferred()

    def startFactory(self):
        if self.started or self.stopped:
            raise RuntimeError
        self.started = 1

    def stopFactory(self):
        if not self.started or self.stopped:
            raise RuntimeError
        self.stopped = 1
        self.whenStopped.callback(True)


class FactoryTestCase(unittest.TestCase):
    """Tests for factories."""

    def test_serverStartStop(self):
        """
        The factory passed to L{IReactorTCP.listenTCP} should be started only
        when it transitions from being used on no ports to being used on one
        port and should be stopped only when it transitions from being used on
        one port to being used on no ports.
        """
        # Note - this test doesn't need to use listenTCP.  It is exercising
        # logic implemented in Factory.doStart and Factory.doStop, so it could
        # just call that directly.  Some other test can make sure that
        # listenTCP and stopListening correctly call doStart and
        # doStop. -exarkun

        f = StartStopFactory()

        # listen on port
        p1 = reactor.listenTCP(0, f, interface='127.0.0.1')
        self.addCleanup(p1.stopListening)

        self.assertEqual((f.started, f.stopped), (1, 0))

        # listen on two more ports
        p2 = reactor.listenTCP(0, f, interface='127.0.0.1')
        p3 = reactor.listenTCP(0, f, interface='127.0.0.1')

        self.assertEqual((f.started, f.stopped), (1, 0))

        # close two ports
        d1 = defer.maybeDeferred(p1.stopListening)
        d2 = defer.maybeDeferred(p2.stopListening)
        closedDeferred = defer.gatherResults([d1, d2])
        def cbClosed(ignored):
            self.assertEqual((f.started, f.stopped), (1, 0))
            # Close the last port
            return p3.stopListening()
        closedDeferred.addCallback(cbClosed)

        def cbClosedAll(ignored):
            self.assertEqual((f.started, f.stopped), (1, 1))
        closedDeferred.addCallback(cbClosedAll)
        return closedDeferred


    def test_clientStartStop(self):
        """
        The factory passed to L{IReactorTCP.connectTCP} should be started when
        the connection attempt starts and stopped when it is over.
        """
        f = ClosingFactory()
        p = reactor.listenTCP(0, f, interface="127.0.0.1")
        f.port = p
        self.addCleanup(f.cleanUp)
        portNumber = p.getHost().port

        factory = ClientStartStopFactory()
        reactor.connectTCP("127.0.0.1", portNumber, factory)
        self.assertTrue(factory.started)
        return loopUntil(lambda: factory.stopped)



class CannotBindTestCase(unittest.TestCase):
    """
    Tests for correct behavior when a reactor cannot bind to the required TCP
    port.
    """

    def test_cannotBind(self):
        """
        L{IReactorTCP.listenTCP} raises L{error.CannotListenError} if the
        address to listen on is already in use.
        """
        f = MyServerFactory()

        p1 = reactor.listenTCP(0, f, interface='127.0.0.1')
        self.addCleanup(p1.stopListening)
        n = p1.getHost().port
        dest = p1.getHost()
        self.assertEqual(dest.type, "TCP")
        self.assertEqual(dest.host, "127.0.0.1")
        self.assertEqual(dest.port, n)

        # make sure new listen raises error
        self.assertRaises(error.CannotListenError,
                          reactor.listenTCP, n, f, interface='127.0.0.1')



    def _fireWhenDoneFunc(self, d, f):
        """Returns closure that when called calls f and then callbacks d.
        """
        @wraps(f)
        def newf(*args, **kw):
            rtn = f(*args, **kw)
            d.callback('')
            return rtn
        return newf


    def test_clientBind(self):
        """
        L{IReactorTCP.connectTCP} calls C{Factory.clientConnectionFailed} with
        L{error.ConnectBindError} if the bind address specified is already in
        use.
        """
        theDeferred = defer.Deferred()
        sf = MyServerFactory()
        sf.startFactory = self._fireWhenDoneFunc(theDeferred, sf.startFactory)
        p = reactor.listenTCP(0, sf, interface="127.0.0.1")
        self.addCleanup(p.stopListening)

        def _connect1(results):
            d = defer.Deferred()
            cf1 = MyClientFactory()
            cf1.buildProtocol = self._fireWhenDoneFunc(d, cf1.buildProtocol)
            reactor.connectTCP("127.0.0.1", p.getHost().port, cf1,
                               bindAddress=("127.0.0.1", 0))
            d.addCallback(_conmade, cf1)
            return d

        def _conmade(results, cf1):
            d = defer.Deferred()
            cf1.protocol.connectionMade = self._fireWhenDoneFunc(
                d, cf1.protocol.connectionMade)
            d.addCallback(_check1connect2, cf1)
            return d

        def _check1connect2(results, cf1):
            self.assertEqual(cf1.protocol.made, 1)

            d1 = defer.Deferred()
            d2 = defer.Deferred()
            port = cf1.protocol.transport.getHost().port
            cf2 = MyClientFactory()
            cf2.clientConnectionFailed = self._fireWhenDoneFunc(
                d1, cf2.clientConnectionFailed)
            cf2.stopFactory = self._fireWhenDoneFunc(d2, cf2.stopFactory)
            reactor.connectTCP("127.0.0.1", p.getHost().port, cf2,
                               bindAddress=("127.0.0.1", port))
            d1.addCallback(_check2failed, cf1, cf2)
            d2.addCallback(_check2stopped, cf1, cf2)
            dl = defer.DeferredList([d1, d2])
            dl.addCallback(_stop, cf1, cf2)
            return dl

        def _check2failed(results, cf1, cf2):
            self.assertEqual(cf2.failed, 1)
            cf2.reason.trap(error.ConnectBindError)
            self.assertTrue(cf2.reason.check(error.ConnectBindError))
            return results

        def _check2stopped(results, cf1, cf2):
            self.assertEqual(cf2.stopped, 1)
            return results

        def _stop(results, cf1, cf2):
            d = defer.Deferred()
            d.addCallback(_check1cleanup, cf1)
            cf1.stopFactory = self._fireWhenDoneFunc(d, cf1.stopFactory)
            cf1.protocol.transport.loseConnection()
            return d

        def _check1cleanup(results, cf1):
            self.assertEqual(cf1.stopped, 1)

        theDeferred.addCallback(_connect1)
        return theDeferred



class MyOtherClientFactory(protocol.ClientFactory):
    def buildProtocol(self, address):
        self.address = address
        self.protocol = AccumulatingProtocol()
        return self.protocol



class LocalRemoteAddressTestCase(unittest.TestCase):
    """
    Tests for correct getHost/getPeer values and that the correct address is
    passed to buildProtocol.
    """
    def test_hostAddress(self):
        """
        L{IListeningPort.getHost} returns the same address as a client
        connection's L{ITCPTransport.getPeer}.
        """
        serverFactory = MyServerFactory()
        serverFactory.protocolConnectionLost = defer.Deferred()
        serverConnectionLost = serverFactory.protocolConnectionLost
        port = reactor.listenTCP(0, serverFactory, interface='127.0.0.1')
        self.addCleanup(port.stopListening)
        n = port.getHost().port

        clientFactory = MyClientFactory()
        onConnection = clientFactory.protocolConnectionMade = defer.Deferred()
        connector = reactor.connectTCP('127.0.0.1', n, clientFactory)

        def check(ignored):
            self.assertEqual([port.getHost()], clientFactory.peerAddresses)
            self.assertEqual(
                port.getHost(), clientFactory.protocol.transport.getPeer())
        onConnection.addCallback(check)

        def cleanup(ignored):
            # Clean up the client explicitly here so that tear down of
            # the server side of the connection begins, then wait for
            # the server side to actually disconnect.
            connector.disconnect()
            return serverConnectionLost
        onConnection.addCallback(cleanup)

        return onConnection



class WriterProtocol(protocol.Protocol):
    def connectionMade(self):
        # use everything ITransport claims to provide. If something here
        # fails, the exception will be written to the log, but it will not
        # directly flunk the test. The test will fail when maximum number of
        # iterations have passed and the writer's factory.done has not yet
        # been set.
        self.transport.write(b"Hello Cleveland!\n")
        seq = [b"Goodbye", b" cruel", b" world", b"\n"]
        self.transport.writeSequence(seq)
        peer = self.transport.getPeer()
        if peer.type != "TCP":
            msg("getPeer returned non-TCP socket: %s" % (peer,))
            self.factory.problem = 1
        us = self.transport.getHost()
        if us.type != "TCP":
            msg("getHost returned non-TCP socket: %s" % (us,))
            self.factory.problem = 1
        self.factory.done = 1

        self.transport.loseConnection()

class ReaderProtocol(protocol.Protocol):
    def dataReceived(self, data):
        self.factory.data += data
    def connectionLost(self, reason):
        self.factory.done = 1

class WriterClientFactory(protocol.ClientFactory):
    def __init__(self):
        self.done = 0
        self.data = b""
    def buildProtocol(self, addr):
        p = ReaderProtocol()
        p.factory = self
        self.protocol = p
        return p

class WriteDataTestCase(unittest.TestCase):
    """
    Test that connected TCP sockets can actually write data. Try to exercise
    the entire ITransport interface.
    """

    def test_writer(self):
        """
        L{ITCPTransport.write} and L{ITCPTransport.writeSequence} send bytes to
        the other end of the connection.
        """
        f = protocol.Factory()
        f.protocol = WriterProtocol
        f.done = 0
        f.problem = 0
        wrappedF = WiredFactory(f)
        p = reactor.listenTCP(0, wrappedF, interface="127.0.0.1")
        self.addCleanup(p.stopListening)
        n = p.getHost().port
        clientF = WriterClientFactory()
        wrappedClientF = WiredFactory(clientF)
        reactor.connectTCP("127.0.0.1", n, wrappedClientF)

        def check(ignored):
            self.failUnless(f.done, "writer didn't finish, it probably died")
            self.failUnless(f.problem == 0, "writer indicated an error")
            self.failUnless(clientF.done,
                            "client didn't see connection dropped")
            expected = b"".join([b"Hello Cleveland!\n",
                                b"Goodbye", b" cruel", b" world", b"\n"])
            self.failUnless(clientF.data == expected,
                            "client didn't receive all the data it expected")
        d = defer.gatherResults([wrappedF.onDisconnect,
                                 wrappedClientF.onDisconnect])
        return d.addCallback(check)


    def test_writeAfterShutdownWithoutReading(self):
        """
        A TCP transport which is written to after the connection has been shut
        down should notify its protocol that the connection has been lost, even
        if the TCP transport is not actively being monitored for read events
        (ie, pauseProducing was called on it).
        """
        # This is an unpleasant thing.  Generally tests shouldn't skip or
        # run based on the name of the reactor being used (most tests
        # shouldn't care _at all_ what reactor is being used, in fact).  The
        # Gtk reactor cannot pass this test, though, because it fails to
        # implement IReactorTCP entirely correctly.  Gtk is quite old at
        # this point, so it's more likely that gtkreactor will be deprecated
        # and removed rather than fixed to handle this case correctly.
        # Since this is a pre-existing (and very long-standing) issue with
        # the Gtk reactor, there's no reason for it to prevent this test
        # being added to exercise the other reactors, for which the behavior
        # was also untested but at least works correctly (now).  See #2833
        # for information on the status of gtkreactor.
        if reactor.__class__.__name__ == 'IOCPReactor':
            raise unittest.SkipTest(
                "iocpreactor does not, in fact, stop reading immediately after "
                "pauseProducing is called. This results in a bonus disconnection "
                "notification. Under some circumstances, it might be possible to "
                "not receive this notifications (specifically, pauseProducing, "
                "deliver some data, proceed with this test).")
        if reactor.__class__.__name__ == 'GtkReactor':
            raise unittest.SkipTest(
                "gtkreactor does not implement unclean disconnection "
                "notification correctly.  This might more properly be "
                "a todo, but due to technical limitations it cannot be.")

        # Called back after the protocol for the client side of the connection
        # has paused its transport, preventing it from reading, therefore
        # preventing it from noticing the disconnection before the rest of the
        # actions which are necessary to trigger the case this test is for have
        # been taken.
        clientPaused = defer.Deferred()

        # Called back when the protocol for the server side of the connection
        # has received connection lost notification.
        serverLost = defer.Deferred()

        class Disconnecter(protocol.Protocol):
            """
            Protocol for the server side of the connection which disconnects
            itself in a callback on clientPaused and publishes notification
            when its connection is actually lost.
            """
            def connectionMade(self):
                """
                Set up a callback on clientPaused to lose the connection.
                """
                msg('Disconnector.connectionMade')
                def disconnect(ignored):
                    msg('Disconnector.connectionMade disconnect')
                    self.transport.loseConnection()
                    msg('loseConnection called')
                clientPaused.addCallback(disconnect)

            def connectionLost(self, reason):
                """
                Notify observers that the server side of the connection has
                ended.
                """
                msg('Disconnecter.connectionLost')
                serverLost.callback(None)
                msg('serverLost called back')

        # Create the server port to which a connection will be made.
        server = protocol.ServerFactory()
        server.protocol = Disconnecter
        port = reactor.listenTCP(0, server, interface='127.0.0.1')
        self.addCleanup(port.stopListening)
        addr = port.getHost()

        @implementer(IPullProducer)
        class Infinite(object):
            """
            A producer which will write to its consumer as long as
            resumeProducing is called.

            @ivar consumer: The L{IConsumer} which will be written to.
            """

            def __init__(self, consumer):
                self.consumer = consumer

            def resumeProducing(self):
                msg('Infinite.resumeProducing')
                self.consumer.write(b'x')
                msg('Infinite.resumeProducing wrote to consumer')

            def stopProducing(self):
                msg('Infinite.stopProducing')


        class UnreadingWriter(protocol.Protocol):
            """
            Trivial protocol which pauses its transport immediately and then
            writes some bytes to it.
            """
            def connectionMade(self):
                msg('UnreadingWriter.connectionMade')
                self.transport.pauseProducing()
                clientPaused.callback(None)
                msg('clientPaused called back')
                def write(ignored):
                    msg('UnreadingWriter.connectionMade write')
                    # This needs to be enough bytes to spill over into the
                    # userspace Twisted send buffer - if it all fits into
                    # the kernel, Twisted won't even poll for OUT events,
                    # which means it won't poll for any events at all, so
                    # the disconnection is never noticed.  This is due to
                    # #1662.  When #1662 is fixed, this test will likely
                    # need to be adjusted, otherwise connection lost
                    # notification will happen too soon and the test will
                    # probably begin to fail with ConnectionDone instead of
                    # ConnectionLost (in any case, it will no longer be
                    # entirely correct).
                    producer = Infinite(self.transport)
                    msg('UnreadingWriter.connectionMade write created producer')
                    self.transport.registerProducer(producer, False)
                    msg('UnreadingWriter.connectionMade write registered producer')
                serverLost.addCallback(write)

        # Create the client and initiate the connection
        client = MyClientFactory()
        client.protocolFactory = UnreadingWriter
        clientConnectionLost = client.deferred
        def cbClientLost(ignored):
            msg('cbClientLost')
            return client.lostReason
        clientConnectionLost.addCallback(cbClientLost)
        msg('Connecting to %s:%s' % (addr.host, addr.port))
        reactor.connectTCP(addr.host, addr.port, client)

        # By the end of the test, the client should have received notification
        # of unclean disconnection.
        msg('Returning Deferred')
        return self.assertFailure(clientConnectionLost, error.ConnectionLost)



class ConnectionLosingProtocol(protocol.Protocol):
    def connectionMade(self):
        self.transport.write(b"1")
        self.transport.loseConnection()
        self.master._connectionMade()
        self.master.ports.append(self.transport)



class NoopProtocol(protocol.Protocol):
    def connectionMade(self):
        self.d = defer.Deferred()
        self.master.serverConns.append(self.d)

    def connectionLost(self, reason):
        self.d.callback(True)



class ConnectionLostNotifyingProtocol(protocol.Protocol):
    """
    Protocol which fires a Deferred which was previously passed to
    its initializer when the connection is lost.

    @ivar onConnectionLost: The L{Deferred} which will be fired in
        C{connectionLost}.

    @ivar lostConnectionReason: C{None} until the connection is lost, then a
        reference to the reason passed to C{connectionLost}.
    """
    def __init__(self, onConnectionLost):
        self.lostConnectionReason = None
        self.onConnectionLost = onConnectionLost


    def connectionLost(self, reason):
        self.lostConnectionReason = reason
        self.onConnectionLost.callback(self)



class HandleSavingProtocol(ConnectionLostNotifyingProtocol):
    """
    Protocol which grabs the platform-specific socket handle and
    saves it as an attribute on itself when the connection is
    established.
    """
    def makeConnection(self, transport):
        """
        Save the platform-specific socket handle for future
        introspection.
        """
        self.handle = transport.getHandle()
        return protocol.Protocol.makeConnection(self, transport)



class ProperlyCloseFilesMixin:
    """
    Tests for platform resources properly being cleaned up.
    """
    def createServer(self, address, portNumber, factory):
        """
        Bind a server port to which connections will be made.  The server
        should use the given protocol factory.

        @return: The L{IListeningPort} for the server created.
        """
        raise NotImplementedError()


    def connectClient(self, address, portNumber, clientCreator):
        """
        Establish a connection to the given address using the given
        L{ClientCreator} instance.

        @return: A Deferred which will fire with the connected protocol instance.
        """
        raise NotImplementedError()


    def getHandleExceptionType(self):
        """
        Return the exception class which will be raised when an operation is
        attempted on a closed platform handle.
        """
        raise NotImplementedError()


    def getHandleErrorCode(self):
        """
        Return the errno expected to result from writing to a closed
        platform socket handle.
        """
        # These platforms have been seen to give EBADF:
        #
        #  Linux 2.4.26, Linux 2.6.15, OS X 10.4, FreeBSD 5.4
        #  Windows 2000 SP 4, Windows XP SP 2
        return errno.EBADF


    def test_properlyCloseFiles(self):
        """
        Test that lost connections properly have their underlying socket
        resources cleaned up.
        """
        onServerConnectionLost = defer.Deferred()
        serverFactory = protocol.ServerFactory()
        serverFactory.protocol = lambda: ConnectionLostNotifyingProtocol(
            onServerConnectionLost)
        serverPort = self.createServer('127.0.0.1', 0, serverFactory)

        onClientConnectionLost = defer.Deferred()
        serverAddr = serverPort.getHost()
        clientCreator = protocol.ClientCreator(
            reactor, lambda: HandleSavingProtocol(onClientConnectionLost))
        clientDeferred = self.connectClient(
            serverAddr.host, serverAddr.port, clientCreator)

        def clientConnected(client):
            """
            Disconnect the client.  Return a Deferred which fires when both
            the client and the server have received disconnect notification.
            """
            client.transport.write(
                b'some bytes to make sure the connection is set up')
            client.transport.loseConnection()
            return defer.gatherResults([
                onClientConnectionLost, onServerConnectionLost])
        clientDeferred.addCallback(clientConnected)

        def clientDisconnected(result):
            """
            Verify that the underlying platform socket handle has been
            cleaned up.
            """
            client, server = result
            client.lostConnectionReason.trap(error.ConnectionClosed)
            server.lostConnectionReason.trap(error.ConnectionClosed)
            expectedErrorCode = self.getHandleErrorCode()
            err = self.assertRaises(
                self.getHandleExceptionType(), client.handle.send, b'bytes')
            self.assertEqual(err.args[0], expectedErrorCode)
        clientDeferred.addCallback(clientDisconnected)

        def cleanup(passthrough):
            """
            Shut down the server port.  Return a Deferred which fires when
            this has completed.
            """
            result = defer.maybeDeferred(serverPort.stopListening)
            result.addCallback(lambda ign: passthrough)
            return result
        clientDeferred.addBoth(cleanup)

        return clientDeferred



class ProperlyCloseFilesTestCase(unittest.TestCase, ProperlyCloseFilesMixin):
    """
    Test that the sockets created by L{IReactorTCP.connectTCP} are cleaned up
    when the connection they are associated with is closed.
    """
    def createServer(self, address, portNumber, factory):
        """
        Create a TCP server using L{IReactorTCP.listenTCP}.
        """
        return reactor.listenTCP(portNumber, factory, interface=address)


    def connectClient(self, address, portNumber, clientCreator):
        """
        Create a TCP client using L{IReactorTCP.connectTCP}.
        """
        return clientCreator.connectTCP(address, portNumber)


    def getHandleExceptionType(self):
        """
        Return L{socket.error} as the expected error type which will be
        raised by a write to the low-level socket object after it has been
        closed.
        """
        return socket.error



class WiredForDeferreds(policies.ProtocolWrapper):
    def __init__(self, factory, wrappedProtocol):
        policies.ProtocolWrapper.__init__(self, factory, wrappedProtocol)

    def connectionMade(self):
        policies.ProtocolWrapper.connectionMade(self)
        self.factory.onConnect.callback(None)

    def connectionLost(self, reason):
        policies.ProtocolWrapper.connectionLost(self, reason)
        self.factory.onDisconnect.callback(None)



class WiredFactory(policies.WrappingFactory):
    protocol = WiredForDeferreds

    def __init__(self, wrappedFactory):
        policies.WrappingFactory.__init__(self, wrappedFactory)
        self.onConnect = defer.Deferred()
        self.onDisconnect = defer.Deferred()



class AddressTestCase(unittest.TestCase):
    """
    Tests for address-related interactions with client and server protocols.
    """
    def setUp(self):
        """
        Create a port and connected client/server pair which can be used
        to test factory behavior related to addresses.

        @return: A L{defer.Deferred} which will be called back when both the
            client and server protocols have received their connection made
            callback.
        """
        class RememberingWrapper(protocol.ClientFactory):
            """
            Simple wrapper factory which records the addresses which are
            passed to its L{buildProtocol} method and delegates actual
            protocol creation to another factory.

            @ivar addresses: A list of the objects passed to buildProtocol.
            @ivar factory: The wrapped factory to which protocol creation is
                delegated.
            """
            def __init__(self, factory):
                self.addresses = []
                self.factory = factory

            # Only bother to pass on buildProtocol calls to the wrapped
            # factory - doStart, doStop, etc aren't necessary for this test
            # to pass.
            def buildProtocol(self, addr):
                """
                Append the given address to C{self.addresses} and forward
                the call to C{self.factory}.
                """
                self.addresses.append(addr)
                return self.factory.buildProtocol(addr)

        # Make a server which we can receive connection and disconnection
        # notification for, and which will record the address passed to its
        # buildProtocol.
        self.server = MyServerFactory()
        self.serverConnMade = self.server.protocolConnectionMade = defer.Deferred()
        self.serverConnLost = self.server.protocolConnectionLost = defer.Deferred()
        # RememberingWrapper is a ClientFactory, but ClientFactory is-a
        # ServerFactory, so this is okay.
        self.serverWrapper = RememberingWrapper(self.server)

        # Do something similar for a client.
        self.client = MyClientFactory()
        self.clientConnMade = self.client.protocolConnectionMade = defer.Deferred()
        self.clientConnLost = self.client.protocolConnectionLost = defer.Deferred()
        self.clientWrapper = RememberingWrapper(self.client)

        self.port = reactor.listenTCP(0, self.serverWrapper, interface='127.0.0.1')
        self.connector = reactor.connectTCP(
            self.port.getHost().host, self.port.getHost().port, self.clientWrapper)

        return defer.gatherResults([self.serverConnMade, self.clientConnMade])


    def tearDown(self):
        """
        Disconnect the client/server pair and shutdown the port created in
        L{setUp}.
        """
        self.connector.disconnect()
        return defer.gatherResults([
            self.serverConnLost, self.clientConnLost,
            defer.maybeDeferred(self.port.stopListening)])


    def test_buildProtocolClient(self):
        """
        L{ClientFactory.buildProtocol} should be invoked with the address of
        the server to which a connection has been established, which should
        be the same as the address reported by the C{getHost} method of the
        transport of the server protocol and as the C{getPeer} method of the
        transport of the client protocol.
        """
        serverHost = self.server.protocol.transport.getHost()
        clientPeer = self.client.protocol.transport.getPeer()

        self.assertEqual(
            self.clientWrapper.addresses,
            [IPv4Address('TCP', serverHost.host, serverHost.port)])
        self.assertEqual(
            self.clientWrapper.addresses,
            [IPv4Address('TCP', clientPeer.host, clientPeer.port)])



class LargeBufferWriterProtocol(protocol.Protocol):

    # Win32 sockets cannot handle single huge chunks of bytes.  Write one
    # massive string to make sure Twisted deals with this fact.

    def connectionMade(self):
        # write 60MB
        self.transport.write(b'X'*self.factory.len)
        self.factory.done = 1
        self.transport.loseConnection()

class LargeBufferReaderProtocol(protocol.Protocol):
    def dataReceived(self, data):
        self.factory.len += len(data)
    def connectionLost(self, reason):
        self.factory.done = 1

class LargeBufferReaderClientFactory(protocol.ClientFactory):
    def __init__(self):
        self.done = 0
        self.len = 0
    def buildProtocol(self, addr):
        p = LargeBufferReaderProtocol()
        p.factory = self
        self.protocol = p
        return p


class FireOnClose(policies.ProtocolWrapper):
    """A wrapper around a protocol that makes it fire a deferred when
    connectionLost is called.
    """
    def connectionLost(self, reason):
        policies.ProtocolWrapper.connectionLost(self, reason)
        self.factory.deferred.callback(None)


class FireOnCloseFactory(policies.WrappingFactory):
    protocol = FireOnClose

    def __init__(self, wrappedFactory):
        policies.WrappingFactory.__init__(self, wrappedFactory)
        self.deferred = defer.Deferred()


class LargeBufferTestCase(unittest.TestCase):
    """Test that buffering large amounts of data works.
    """

    datalen = 60*1024*1024
    def testWriter(self):
        f = protocol.Factory()
        f.protocol = LargeBufferWriterProtocol
        f.done = 0
        f.problem = 0
        f.len = self.datalen
        wrappedF = FireOnCloseFactory(f)
        p = reactor.listenTCP(0, wrappedF, interface="127.0.0.1")
        self.addCleanup(p.stopListening)
        n = p.getHost().port
        clientF = LargeBufferReaderClientFactory()
        wrappedClientF = FireOnCloseFactory(clientF)
        reactor.connectTCP("127.0.0.1", n, wrappedClientF)

        d = defer.gatherResults([wrappedF.deferred, wrappedClientF.deferred])
        def check(ignored):
            self.failUnless(f.done, "writer didn't finish, it probably died")
            self.failUnless(clientF.len == self.datalen,
                            "client didn't receive all the data it expected "
                            "(%d != %d)" % (clientF.len, self.datalen))
            self.failUnless(clientF.done,
                            "client didn't see connection dropped")
        return d.addCallback(check)


@implementer(IHalfCloseableProtocol)
class MyHCProtocol(AccumulatingProtocol):


    readHalfClosed = False
    writeHalfClosed = False

    def readConnectionLost(self):
        self.readHalfClosed = True
        # Invoke notification logic from the base class to simplify testing.
        if self.writeHalfClosed:
            self.connectionLost(None)

    def writeConnectionLost(self):
        self.writeHalfClosed = True
        # Invoke notification logic from the base class to simplify testing.
        if self.readHalfClosed:
            self.connectionLost(None)


class MyHCFactory(protocol.ServerFactory):

    called = 0
    protocolConnectionMade = None

    def buildProtocol(self, addr):
        self.called += 1
        p = MyHCProtocol()
        p.factory = self
        self.protocol = p
        return p


class HalfCloseTestCase(unittest.TestCase):
    """Test half-closing connections."""

    def setUp(self):
        self.f = f = MyHCFactory()
        self.p = p = reactor.listenTCP(0, f, interface="127.0.0.1")
        self.addCleanup(p.stopListening)
        d = loopUntil(lambda :p.connected)

        self.cf = protocol.ClientCreator(reactor, MyHCProtocol)

        d.addCallback(lambda _: self.cf.connectTCP(p.getHost().host,
                                                   p.getHost().port))
        d.addCallback(self._setUp)
        return d

    def _setUp(self, client):
        self.client = client
        self.clientProtoConnectionLost = self.client.closedDeferred = defer.Deferred()
        self.assertEqual(self.client.transport.connected, 1)
        # Wait for the server to notice there is a connection, too.
        return loopUntil(lambda: getattr(self.f, 'protocol', None) is not None)

    def tearDown(self):
        self.assertEqual(self.client.closed, 0)
        self.client.transport.loseConnection()
        d = defer.maybeDeferred(self.p.stopListening)
        d.addCallback(lambda ign: self.clientProtoConnectionLost)
        d.addCallback(self._tearDown)
        return d

    def _tearDown(self, ignored):
        self.assertEqual(self.client.closed, 1)
        # because we did half-close, the server also needs to
        # closed explicitly.
        self.assertEqual(self.f.protocol.closed, 0)
        d = defer.Deferred()
        def _connectionLost(reason):
            self.f.protocol.closed = 1
            d.callback(None)
        self.f.protocol.connectionLost = _connectionLost
        self.f.protocol.transport.loseConnection()
        d.addCallback(lambda x:self.assertEqual(self.f.protocol.closed, 1))
        return d

    def testCloseWriteCloser(self):
        client = self.client
        f = self.f
        t = client.transport

        t.write(b"hello")
        d = loopUntil(lambda :len(t._tempDataBuffer) == 0)
        def loseWrite(ignored):
            t.loseWriteConnection()
            return loopUntil(lambda :t._writeDisconnected)
        def check(ignored):
            self.assertEqual(client.closed, False)
            self.assertEqual(client.writeHalfClosed, True)
            self.assertEqual(client.readHalfClosed, False)
            return loopUntil(lambda :f.protocol.readHalfClosed)
        def write(ignored):
            w = client.transport.write
            w(b" world")
            w(b"lalala fooled you")
            self.assertEqual(0, len(client.transport._tempDataBuffer))
            self.assertEqual(f.protocol.data, b"hello")
            self.assertEqual(f.protocol.closed, False)
            self.assertEqual(f.protocol.readHalfClosed, True)
        return d.addCallback(loseWrite).addCallback(check).addCallback(write)

    def testWriteCloseNotification(self):
        f = self.f
        f.protocol.transport.loseWriteConnection()

        d = defer.gatherResults([
            loopUntil(lambda :f.protocol.writeHalfClosed),
            loopUntil(lambda :self.client.readHalfClosed)])
        d.addCallback(lambda _: self.assertEqual(
            f.protocol.readHalfClosed, False))
        return d


class HalfClose2TestCase(unittest.TestCase):

    def setUp(self):
        self.f = f = MyServerFactory()
        self.f.protocolConnectionMade = defer.Deferred()
        self.p = p = reactor.listenTCP(0, f, interface="127.0.0.1")

        # XXX we don't test server side yet since we don't do it yet
        d = protocol.ClientCreator(reactor, AccumulatingProtocol).connectTCP(
            p.getHost().host, p.getHost().port)
        d.addCallback(self._gotClient)
        return d

    def _gotClient(self, client):
        self.client = client
        # Now wait for the server to catch up - it doesn't matter if this
        # Deferred has already fired and gone away, in that case we'll
        # return None and not wait at all, which is precisely correct.
        return self.f.protocolConnectionMade

    def tearDown(self):
        self.client.transport.loseConnection()
        return self.p.stopListening()

    def testNoNotification(self):
        """
        TCP protocols support half-close connections, but not all of them
        support being notified of write closes.  In this case, test that
        half-closing the connection causes the peer's connection to be
        closed.
        """
        self.client.transport.write(b"hello")
        self.client.transport.loseWriteConnection()
        self.f.protocol.closedDeferred = d = defer.Deferred()
        self.client.closedDeferred = d2 = defer.Deferred()
        d.addCallback(lambda x:
                      self.assertEqual(self.f.protocol.data, b'hello'))
        d.addCallback(lambda x: self.assertEqual(self.f.protocol.closed, True))
        return defer.gatherResults([d, d2])

    def testShutdownException(self):
        """
        If the other side has already closed its connection,
        loseWriteConnection should pass silently.
        """
        self.f.protocol.transport.loseConnection()
        self.client.transport.write(b"X")
        self.client.transport.loseWriteConnection()
        self.f.protocol.closedDeferred = d = defer.Deferred()
        self.client.closedDeferred = d2 = defer.Deferred()
        d.addCallback(lambda x:
                      self.assertEqual(self.f.protocol.closed, True))
        return defer.gatherResults([d, d2])


class HalfCloseBuggyApplicationTests(unittest.TestCase):
    """
    Test half-closing connections where notification code has bugs.
    """

    def setUp(self):
        """
        Set up a server and connect a client to it.  Return a Deferred which
        only fires once this is done.
        """
        self.serverFactory = MyHCFactory()
        self.serverFactory.protocolConnectionMade = defer.Deferred()
        self.port = reactor.listenTCP(
            0, self.serverFactory, interface="127.0.0.1")
        self.addCleanup(self.port.stopListening)
        addr = self.port.getHost()
        creator = protocol.ClientCreator(reactor, MyHCProtocol)
        clientDeferred = creator.connectTCP(addr.host, addr.port)
        def setClient(clientProtocol):
            self.clientProtocol = clientProtocol
        clientDeferred.addCallback(setClient)
        return defer.gatherResults([
            self.serverFactory.protocolConnectionMade,
            clientDeferred])


    def aBug(self, *args):
        """
        Fake implementation of a callback which illegally raises an
        exception.
        """
        raise RuntimeError("ONO I AM BUGGY CODE")


    def _notificationRaisesTest(self):
        """
        Helper for testing that an exception is logged by the time the
        client protocol loses its connection.
        """
        closed = self.clientProtocol.closedDeferred = defer.Deferred()
        self.clientProtocol.transport.loseWriteConnection()
        def check(ignored):
            errors = self.flushLoggedErrors(RuntimeError)
            self.assertEqual(len(errors), 1)
        closed.addCallback(check)
        return closed


    def test_readNotificationRaises(self):
        """
        If C{readConnectionLost} raises an exception when the transport
        calls it to notify the protocol of that event, the exception should
        be logged and the protocol should be disconnected completely.
        """
        self.serverFactory.protocol.readConnectionLost = self.aBug
        return self._notificationRaisesTest()


    def test_writeNotificationRaises(self):
        """
        If C{writeConnectionLost} raises an exception when the transport
        calls it to notify the protocol of that event, the exception should
        be logged and the protocol should be disconnected completely.
        """
        self.clientProtocol.writeConnectionLost = self.aBug
        return self._notificationRaisesTest()



class LogTestCase(unittest.TestCase):
    """
    Test logging facility of TCP base classes.
    """

    def test_logstrClientSetup(self):
        """
        Check that the log customization of the client transport happens
        once the client is connected.
        """
        server = MyServerFactory()

        client = MyClientFactory()
        client.protocolConnectionMade = defer.Deferred()

        port = reactor.listenTCP(0, server, interface='127.0.0.1')
        self.addCleanup(port.stopListening)

        connector = reactor.connectTCP(
            port.getHost().host, port.getHost().port, client)
        self.addCleanup(connector.disconnect)

        # It should still have the default value
        self.assertEqual(connector.transport.logstr,
                          "Uninitialized")

        def cb(ign):
            self.assertEqual(connector.transport.logstr,
                              "AccumulatingProtocol,client")
        client.protocolConnectionMade.addCallback(cb)
        return client.protocolConnectionMade



class PauseProducingTestCase(unittest.TestCase):
    """
    Test some behaviors of pausing the production of a transport.
    """

    def test_pauseProducingInConnectionMade(self):
        """
        In C{connectionMade} of a client protocol, C{pauseProducing} used to be
        ignored: this test is here to ensure it's not ignored.
        """
        server = MyServerFactory()

        client = MyClientFactory()
        client.protocolConnectionMade = defer.Deferred()

        port = reactor.listenTCP(0, server, interface='127.0.0.1')
        self.addCleanup(port.stopListening)

        connector = reactor.connectTCP(
            port.getHost().host, port.getHost().port, client)
        self.addCleanup(connector.disconnect)

        def checkInConnectionMade(proto):
            tr = proto.transport
            # The transport should already be monitored
            self.assertIn(tr, reactor.getReaders() +
                              reactor.getWriters())
            proto.transport.pauseProducing()
            self.assertNotIn(tr, reactor.getReaders() +
                                 reactor.getWriters())
            d = defer.Deferred()
            d.addCallback(checkAfterConnectionMade)
            reactor.callLater(0, d.callback, proto)
            return d
        def checkAfterConnectionMade(proto):
            tr = proto.transport
            # The transport should still not be monitored
            self.assertNotIn(tr, reactor.getReaders() +
                                 reactor.getWriters())
        client.protocolConnectionMade.addCallback(checkInConnectionMade)
        return client.protocolConnectionMade

    if not interfaces.IReactorFDSet.providedBy(reactor):
        test_pauseProducingInConnectionMade.skip = "Reactor not providing IReactorFDSet"



class CallBackOrderTestCase(unittest.TestCase):
    """
    Test the order of reactor callbacks
    """

    def test_loseOrder(self):
        """
        Check that Protocol.connectionLost is called before factory's
        clientConnectionLost
        """
        server = MyServerFactory()
        server.protocolConnectionMade = (defer.Deferred()
                .addCallback(lambda proto: self.addCleanup(
                             proto.transport.loseConnection)))

        client = MyClientFactory()
        client.protocolConnectionLost = defer.Deferred()
        client.protocolConnectionMade = defer.Deferred()

        def _cbCM(res):
            """
            protocol.connectionMade callback
            """
            reactor.callLater(0, client.protocol.transport.loseConnection)

        client.protocolConnectionMade.addCallback(_cbCM)

        port = reactor.listenTCP(0, server, interface='127.0.0.1')
        self.addCleanup(port.stopListening)

        connector = reactor.connectTCP(
            port.getHost().host, port.getHost().port, client)
        self.addCleanup(connector.disconnect)

        def _cbCCL(res):
            """
            factory.clientConnectionLost callback
            """
            return 'CCL'

        def _cbCL(res):
            """
            protocol.connectionLost callback
            """
            return 'CL'

        def _cbGather(res):
            self.assertEqual(res, ['CL', 'CCL'])

        d = defer.gatherResults([
                client.protocolConnectionLost.addCallback(_cbCL),
                client.deferred.addCallback(_cbCCL)])
        return d.addCallback(_cbGather)



try:
    import resource
except ImportError:
    pass
else:
    numRounds = resource.getrlimit(resource.RLIMIT_NOFILE)[0] + 10
    ProperlyCloseFilesTestCase.numberRounds = numRounds