aboutsummaryrefslogtreecommitdiff
path: root/nxcomp/Transport.cpp
blob: 21012a8c4bdee095b3edb47a576d656c0e33d858 (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
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
/**************************************************************************/
/*                                                                        */
/* Copyright (c) 2001, 2009 NoMachine, http://www.nomachine.com/.         */
/*                                                                        */
/* NXCOMP, NX protocol compression and NX extensions to this software     */
/* are copyright of NoMachine. Redistribution and use of the present      */
/* software is allowed according to terms specified in the file LICENSE   */
/* which comes in the source distribution.                                */
/*                                                                        */
/* Check http://www.nomachine.com/licensing.html for applicability.       */
/*                                                                        */
/* NX and NoMachine are trademarks of Medialogic S.p.A.                   */
/*                                                                        */
/* All rights reserved.                                                   */
/*                                                                        */
/**************************************************************************/

#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/socket.h>

#include "Transport.h"

#include "Statistics.h"

//
// Set the verbosity level. You also
// need to define DUMP in Misc.cpp
// if DUMP is defined here.
//

#define PANIC
#define WARNING
#undef  TEST
#undef  DEBUG
#undef  INSPECT
#undef  DUMP

//
// Used to lock and unlock the transport
// buffers before they are accessed by
// different threads.
//

#undef  THREADS

//
// Define this to get logging all the
// operations performed by the parent
// thread, the one that enqueues and
// dequeues data.
//

#define PARENT

//
// Define this to know when a channel
// is created or destroyed.
//

#undef  REFERENCES

//
// Reference count for allocated buffers.
//

#ifdef REFERENCES

int Transport::references_;
int ProxyTransport::references_;
int InternalTransport::references_;

#endif

//
// This is the base class providing methods for read
// and write buffering.
//

Transport::Transport(int fd) : fd_(fd)
{
  #ifdef TEST
  *logofs << "Transport: Going to create base transport "
          << "for FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  type_ = transport_base;

  //
  // Set up the write buffer.
  //

  w_buffer_.length_ = 0;
  w_buffer_.start_  = 0;

  initialSize_   = TRANSPORT_BUFFER_DEFAULT_SIZE;
  thresholdSize_ = TRANSPORT_BUFFER_DEFAULT_SIZE << 1;
  maximumSize_   = TRANSPORT_BUFFER_DEFAULT_SIZE << 4;

  w_buffer_.data_.resize(initialSize_);

  //
  // Set non-blocking IO on socket.
  //

  SetNonBlocking(fd_, 1);

  blocked_ = 0;
  finish_  = 0;

  #ifdef REFERENCES
  *logofs << "Transport: Created new object at " 
          << this << " out of " << ++references_ 
          << " allocated references.\n" << logofs_flush;
  #endif
}

Transport::~Transport()
{
  #ifdef TEST
  *logofs << "Transport: Going to destroy base class "
          << "for FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  ::close(fd_);

  #ifdef REFERENCES
  *logofs << "Transport: Deleted object at " 
          << this << " out of " << --references_ 
          << " allocated references.\n" << logofs_flush;
  #endif
}

//
// Read data from its file descriptor.
//

int Transport::read(unsigned char *data, unsigned int size)
{
  #ifdef DEBUG
  *logofs << "Transport: Going to read " << size << " bytes from " 
          << "FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  //
  // Read the available data from the socket.
  //

  int result = ::read(fd_, data, size);

  //
  // Update the current timestamp as the read
  // can have scheduled some other process.
  //

  getNewTimestamp();

  if (result < 0)
  {
    if (EGET() == EAGAIN)
    {
      #ifdef TEST
      *logofs << "Transport: WARNING! Read of " << size << " bytes from "
              << "FD#" << fd_ << " would block.\n" << logofs_flush;
      #endif

      return 0;
    }
    else if (EGET() == EINTR)
    {
      #ifdef TEST
      *logofs << "Transport: Read of " << size << " bytes from "
              << "FD#" << fd_ << " was interrupted.\n"
              << logofs_flush;
      #endif

      return 0;
    }
    else
    {
      #ifdef TEST
      *logofs << "Transport: Error reading from " 
              << "FD#" << fd_ << ".\n" << logofs_flush;
      #endif

      finish();

      return -1;
    }
  }
  else if (result == 0)
  {
    #ifdef TEST
    *logofs << "Transport: No data read from " 
            << "FD#" << fd_ << ".\n" << logofs_flush;
    #endif

    finish();

    return -1;
  }

  #ifdef TEST
  *logofs << "Transport: Read " << result << " bytes out of "
          << size << " from FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  #ifdef DUMP

  *logofs << "Transport: Dumping content of read data.\n"
          << logofs_flush;

  DumpData(data, result);

  #endif

  return result;
}

//
// Write as many bytes as possible to socket. 
// Append the remaining data bytes to the end 
// of the buffer and update length to reflect
// changes.
//

int Transport::write(T_write type, const unsigned char *data, const unsigned int size)
{
  //
  // If an immediate write was requested then
  // flush the enqueued data first.
  //
  // Alternatively may try to write only if
  // the socket is not blocked.
  //
  // if (w_buffer_.length_ > 0 && blocked_ == 0 &&
  //         type == write_immediate)
  // {
  //   ...
  // }
  //

  if (w_buffer_.length_ > 0 && type == write_immediate)

  {
    #ifdef TEST
    *logofs << "Transport: Writing " << w_buffer_.length_
            << " bytes of previous data to FD#" << fd_ << ".\n"
            << logofs_flush;
    #endif

    int result = Transport::flush();

    if (result < 0)
    {
      return -1;
    }
  }

  //
  // If nothing is remained, write immediately
  // to the socket.
  //

  unsigned int written = 0;

  if (w_buffer_.length_ == 0 && blocked_ == 0 &&
          type == write_immediate)
  {
    //
    // Limit the amount of data sent.
    //

    unsigned int toWrite = size;

    #ifdef DUMP

    *logofs << "Transport: Going to write " << toWrite
            << " bytes to FD#" << fd_ << " with checksum ";

    DumpChecksum(data, size);

    *logofs << ".\n" << logofs_flush;

    #endif

    T_timestamp writeTs;

    int diffTs;

    while (written < toWrite)
    {
      //
      // Trace system time spent writing data.
      //

      writeTs = getTimestamp();

      int result = ::write(fd_, data + written, toWrite - written);

      diffTs = diffTimestamp(writeTs, getNewTimestamp());

      statistics -> addWriteTime(diffTs);

      if (result <= 0)
      {
        if (EGET() == EAGAIN)
        {
          #ifdef TEST
          *logofs << "Transport: Write of " << toWrite - written
                  << " bytes on FD#" << fd_ << " would block.\n"
                  << logofs_flush;
          #endif

          blocked_ = 1;

          break;
        }
        else if (EGET() == EINTR)
        {
          #ifdef TEST
          *logofs << "Transport: Write of " << toWrite - written
                  << " bytes on FD#" << fd_ << " was interrupted.\n"
                  << logofs_flush;
          #endif

          continue;
        }
        else
        {
          #ifdef TEST
          *logofs << "Transport: Write to " << "FD#" 
                  << fd_ << " failed.\n" << logofs_flush;
          #endif

          finish();

          return -1;
        }
      }
      else
      {
        #ifdef TEST
        *logofs << "Transport: Immediately written " << result
                << " bytes on " << "FD#" << fd_ << ".\n"
                << logofs_flush;
        #endif

        written += result;
      }
    }

    #ifdef DUMP

    if (written > 0)
    {
      *logofs << "Transport: Dumping content of immediately written data.\n"
              << logofs_flush;

      DumpData(data, written);
    }

    #endif
  }

  if (written == size)
  {
    //
    // We will not affect the write buffer.
    //

    return written;
  }

  #ifdef DEBUG
  *logofs << "Transport: Going to append " << size - written
          << " bytes to write buffer for " << "FD#" << fd_
          << ".\n" << logofs_flush;
  #endif

  if (resize(w_buffer_, size - written) < 0)
  {
    return -1;
  }

  memmove(w_buffer_.data_.begin() + w_buffer_.start_ + w_buffer_.length_,
              data + written, size - written);

  w_buffer_.length_ += size - written;

  #ifdef TEST
  *logofs << "Transport: Write buffer for FD#" << fd_
          << " has data for " << w_buffer_.length_ << " bytes.\n"
          << logofs_flush;

  *logofs << "Transport: Start is " << w_buffer_.start_ 
          << " length is " << w_buffer_.length_ << " size is "
          << w_buffer_.data_.size() << " capacity is "
          << w_buffer_.data_.capacity() << ".\n"
          << logofs_flush;
  #endif

  //
  // Note that this function always returns the whole
  // size of buffer that was provided, either if not
  // all the data could be actually written.
  //

  return size;
}

//
// Write pending data to its file descriptor.
//

int Transport::flush()
{
  if (w_buffer_.length_ == 0)
  {
    #ifdef TEST
    *logofs << "Transport: No data to flush on "
            << "FD#" << fd_ << ".\n" << logofs_flush;
    #endif

    #ifdef WARNING
    if (blocked_ != 0)
    {
      *logofs << "Transport: Blocked flag is " << blocked_
              << " with no data to flush on FD#" << fd_
              << ".\n" << logofs_flush;
    }
    #endif

    return 0;
  }

  //
  // It's time to move data from the 
  // write buffer to the real link. 
  //

  int written = 0;

  int toWrite = w_buffer_.length_;

  //
  // We will do our best to write any available
  // data to the socket, so let's say we start
  // from a clean state.
  //

  blocked_ = 0;

  #ifdef TEST
  *logofs << "Transport: Going to flush " << toWrite
          << " bytes on FD#" << fd_ << ".\n"
          << logofs_flush;
  #endif

  T_timestamp writeTs;

  int diffTs;

  while (written < toWrite)
  {
    writeTs = getTimestamp();

    int result = ::write(fd_, w_buffer_.data_.begin() + w_buffer_.start_ +
                             written, toWrite - written);

    diffTs = diffTimestamp(writeTs, getNewTimestamp());

    statistics -> addWriteTime(diffTs);

    if (result <= 0)
    {
      if (EGET() == EAGAIN)
      {
        #ifdef TEST
        *logofs << "Transport: Write of " << toWrite - written
                << " bytes on FD#" << fd_ << " would block.\n"
                << logofs_flush;
        #endif

        blocked_ = 1;

        break;
      }
      else if (EGET() == EINTR)
      {
        #ifdef TEST
        *logofs << "Transport: Write of " << toWrite - written
                << " bytes on FD#" << fd_ << " was interrupted.\n"
                << logofs_flush;
        #endif

        continue;
      }
      else
      {
        #ifdef TEST
        *logofs << "Transport: Write to " << "FD#" 
                << fd_ << " failed.\n" << logofs_flush;
        #endif

        finish();

        return -1;
      }
    }
    else
    {
      #ifdef TEST
      *logofs << "Transport: Flushed " << result << " bytes on " 
              << "FD#" << fd_ << ".\n" << logofs_flush;
      #endif

      written += result;
    }
  }

  if (written > 0)
  {
    #ifdef DUMP

    *logofs << "Transport: Dumping content of flushed data.\n"
            << logofs_flush;

    DumpData(w_buffer_.data_.begin() + w_buffer_.start_, written);

    #endif

    //
    // Update the buffer status.
    //

    w_buffer_.length_ -= written;

    if (w_buffer_.length_ == 0)
    {
      w_buffer_.start_ = 0;
    }
    else
    {
      w_buffer_.start_ += written;
    }
  }

  //
  // It can be that we wrote less bytes than
  // available because of the write limit.
  //

  if (w_buffer_.length_ > 0)
  {
    #ifdef TEST
    *logofs << "Transport: There are still " << w_buffer_.length_ 
            << " bytes in write buffer for " << "FD#" 
            << fd_ << ".\n" << logofs_flush;
    #endif

    blocked_ = 1;
  }

  #ifdef TEST
  *logofs << "Transport: Write buffer for FD#" << fd_
          << " has data for " << w_buffer_.length_ << " bytes.\n"
          << logofs_flush;

  *logofs << "Transport: Start is " << w_buffer_.start_ 
          << " length is " << w_buffer_.length_ << " size is "
          << w_buffer_.data_.size() << " capacity is "
          << w_buffer_.data_.capacity() << ".\n"
          << logofs_flush;
  #endif

  //
  // No new data was produced for the link except
  // any outstanding data from previous writes.
  //

  return 0;
}

int Transport::drain(int limit, int timeout)
{
  if (w_buffer_.length_ <= limit)
  {
    return 1;
  }

  //
  // Write the data accumulated in the write
  // buffer until it is below the limit or
  // the timeout is elapsed.
  //

  int toWrite = w_buffer_.length_;

  int written = 0;

  #ifdef TEST
  *logofs << "Transport: Draining " << toWrite - limit
          << " bytes on FD#" << fd_ << " with limit set to "
          << limit << ".\n" << logofs_flush;
  #endif

  T_timestamp startTs = getNewTimestamp();

  T_timestamp selectTs;
  T_timestamp writeTs;
  T_timestamp idleTs;

  T_timestamp nowTs = startTs;

  int diffTs;

  fd_set writeSet;
  fd_set readSet;

  FD_ZERO(&writeSet);
  FD_ZERO(&readSet);

  int result;
  int ready;

  while (w_buffer_.length_ - written > limit)
  {
    nowTs = getNewTimestamp();

    //
    // Wait for descriptor to become
    // readable or writable.
    //

    FD_SET(fd_, &writeSet);
    FD_SET(fd_, &readSet);

    setTimestamp(selectTs, timeout / 2);

    idleTs = nowTs;

    result = select(fd_ + 1, &readSet, &writeSet, NULL, &selectTs);

    nowTs = getNewTimestamp();

    diffTs = diffTimestamp(idleTs, nowTs);

    statistics -> addIdleTime(diffTs);

    statistics -> subReadTime(diffTs);

    if (result < 0)
    {
      if (EGET() == EINTR)
      {
        #ifdef TEST
        *logofs << "Transport: Select on FD#" << fd_
                << " was interrupted.\n" << logofs_flush;
        #endif

        continue;
      }
      else
      {
        #ifdef TEST
        *logofs << "Transport: Select on FD#" << fd_
                << " failed.\n" << logofs_flush;
        #endif

        finish();

        return -1;
      }
    }
    else if (result > 0)
    {
      ready = result;

      if (FD_ISSET(fd_, &writeSet))
      {
        writeTs = getNewTimestamp();

        result = ::write(fd_, w_buffer_.data_.begin() + w_buffer_.start_ +
                             written, toWrite - written);

        nowTs = getNewTimestamp();

        diffTs = diffTimestamp(writeTs, nowTs);

        statistics -> addWriteTime(diffTs);

        if (result > 0)
        {
          #ifdef TEST
          *logofs << "Transport: Forced flush of " << result
                  << " bytes on " << "FD#" << fd_ << ".\n"
                  << logofs_flush;
          #endif

          written += result;
        }
        else if (result < 0 && EGET() == EINTR)
        {
          #ifdef TEST
          *logofs << "Transport: Write to FD#" << fd_
                  << " was interrupted.\n" << logofs_flush;
          #endif

          continue;
        }
        else
        {
          #ifdef TEST
          *logofs << "Transport: Write to FD#" << fd_
                  << " failed.\n" << logofs_flush;
          #endif

          finish();

          return -1;
        }

        ready--;
      }

      if (ready > 0)
      {
        if (FD_ISSET(fd_, &readSet))
        {
          #ifdef TEST
          *logofs << "Transport: Not draining further "
                  << "due to data readable on FD#" << fd_
                  << ".\n" << logofs_flush;
          #endif

          break;
        }
      }
    }
    #ifdef TEST
    else
    {
      *logofs << "Transport: Timeout encountered "
              << "waiting for FD#" << fd_ << ".\n"
              << logofs_flush;
    }
    #endif

    nowTs = getNewTimestamp();

    diffTs = diffTimestamp(startTs, nowTs);

    if (diffTs >= timeout)
    {
      #ifdef TEST
      *logofs << "Transport: Not draining further "
              << "due to the timeout on FD#" << fd_
              << ".\n" << logofs_flush;
      #endif

      break;
    }
  }

  if (written > 0)
  {
    #ifdef DUMP

    *logofs << "Transport: Dumping content of flushed data.\n"
            << logofs_flush;

    DumpData(w_buffer_.data_.begin() + w_buffer_.start_, written);

    #endif

    //
    // Update the buffer status.
    //

    w_buffer_.length_ -= written;

    if (w_buffer_.length_ == 0)
    {
      w_buffer_.start_ = 0;

      blocked_ = 0;
    }
    else
    {
      w_buffer_.start_ += written;

      #ifdef TEST
      *logofs << "Transport: There are still " << w_buffer_.length_ 
              << " bytes in write buffer for " << "FD#" 
              << fd_ << ".\n" << logofs_flush;
      #endif

      blocked_ = 1;
    }
  }
  #ifdef TEST
  else
  {
    *logofs << "Transport: WARNING! No data written to FD#" << fd_
            << " with " << toWrite  << " bytes to drain and limit "
            << "set to " << limit << ".\n" << logofs_flush;
  }
  #endif

  #ifdef TEST
  *logofs << "Transport: Write buffer for FD#" << fd_
          << " has data for " << w_buffer_.length_ << " bytes.\n"
          << logofs_flush;

  *logofs << "Transport: Start is " << w_buffer_.start_ 
          << " length is " << w_buffer_.length_ << " size is "
          << w_buffer_.data_.size() << " capacity is "
          << w_buffer_.data_.capacity() << ".\n"
          << logofs_flush;
  #endif

  return (w_buffer_.length_ <= limit);
}

int Transport::wait(int timeout) const
{
  T_timestamp startTs = getNewTimestamp();

  T_timestamp idleTs;
  T_timestamp selectTs;

  T_timestamp nowTs = startTs;

  long available = 0;
  int  result    = 0;

  int diffTs;

  fd_set readSet;

  FD_ZERO(&readSet);
  FD_SET(fd_, &readSet);

  for (;;)
  {
    available = readable();

    diffTs = diffTimestamp(startTs, nowTs);

    if (available != 0 || timeout == 0 ||
            (diffTs + (timeout / 10)) >= timeout)
    {
      #ifdef TEST
      *logofs << "Transport: There are " << available
              << " bytes on FD#" << fd_ << " after "
              << diffTs << " Ms.\n" << logofs_flush;
      #endif

      return available;
    }
    else if (available == 0 && result > 0)
    {
      #ifdef TEST
      *logofs << "Transport: Read on " << "FD#" 
              << fd_ << " failed.\n" << logofs_flush;
      #endif

      return -1;
    }

    //
    // TODO: Should subtract the time
    // already spent in select.
    //

    selectTs.tv_sec  = 0;
    selectTs.tv_usec = timeout * 1000;

    idleTs = nowTs;

    //
    // Wait for descriptor to become readable.
    //

    result = select(fd_ + 1, &readSet, NULL, NULL, &selectTs);

    nowTs = getNewTimestamp();

    diffTs = diffTimestamp(idleTs, nowTs);

    statistics -> addIdleTime(diffTs);

    statistics -> subReadTime(diffTs);

    if (result < 0)
    {
      if (EGET() == EINTR)
      {
        #ifdef TEST
        *logofs << "Transport: Select on FD#" << fd_
                << " was interrupted.\n" << logofs_flush;
        #endif

        continue;
      }
      else
      {
        #ifdef TEST
        *logofs << "Transport: Select on " << "FD#" 
                << fd_ << " failed.\n" << logofs_flush;
        #endif

        return -1;
      }
    }
    #ifdef TEST
    else if (result == 0)
    {
      *logofs << "Transport: No data available on FD#" << fd_
              << " after " << diffTimestamp(startTs, nowTs)
              << " Ms.\n" << logofs_flush;
    }
    else
    {
      *logofs << "Transport: Data became available on FD#" << fd_
              << " after " << diffTimestamp(startTs, nowTs)
              << " Ms.\n" << logofs_flush;
    }
    #endif
  }
}

void Transport::setSize(unsigned int initialSize, unsigned int thresholdSize,
                            unsigned int maximumSize)
{
  initialSize_   = initialSize;
  thresholdSize_ = thresholdSize;
  maximumSize_   = maximumSize;

  #ifdef TEST
  *logofs << "Transport: Set buffer sizes for FD#" << fd_
          << " to " << initialSize_ << "/" << thresholdSize_
          << "/" << maximumSize_ << ".\n" << logofs_flush;
  #endif
}

void Transport::fullReset()
{
  blocked_ = 0;
  finish_  = 0;

  fullReset(w_buffer_);
}

int Transport::resize(T_buffer &buffer, const int &size)
{
  if ((int) buffer.data_.size() >= (buffer.length_ + size) &&
          (buffer.start_ + buffer.length_ + size) >
               (int) buffer.data_.size())
  {
    if (buffer.length_ > 0)
    {
      //
      // There is enough space in buffer but we need
      // to move existing data at the beginning.
      //

      #ifdef TEST
      *logofs << "Transport: Moving " << buffer.length_
              << " bytes of data for " << "FD#" << fd_
              << " to make room in the buffer.\n"
              << logofs_flush;
      #endif

      memmove(buffer.data_.begin(), buffer.data_.begin() +
                  buffer.start_, buffer.length_);
    }

    buffer.start_ = 0;

    #ifdef DEBUG
    *logofs << "Transport: Made room for " 
            << buffer.data_.size() - buffer.start_
            << " bytes in buffer for " << "FD#" 
            << fd_ << ".\n" << logofs_flush;
    #endif
  }
  else if ((buffer.length_ + size) > (int) buffer.data_.size())
  {
    //
    // Not enough space, so increase
    // the size of the buffer.
    //

    if (buffer.start_ != 0 && buffer.length_ > 0)
    {
      #ifdef TEST
      *logofs << "Transport: Moving " << buffer.length_
              << " bytes of data for " << "FD#" << fd_
              << " to resize the buffer.\n"
              << logofs_flush;
      #endif

      memmove(buffer.data_.begin(), buffer.data_.begin() +
                  buffer.start_, buffer.length_);
    }

    buffer.start_ = 0;

    unsigned int newSize = thresholdSize_;

    while (newSize < (unsigned int) buffer.length_ + size)
    {
      newSize <<= 1;

      if (newSize >= maximumSize_)
      {
        newSize = buffer.length_ + size + initialSize_;
      }
    }

    #ifdef DEBUG
    *logofs << "Transport: Buffer for " << "FD#" << fd_
            << " will be enlarged from " << buffer.data_.size()
            << " to at least " << buffer.length_ + size
            << " bytes.\n" << logofs_flush;
    #endif

    buffer.data_.resize(newSize);

    #ifdef TEST
    if (newSize >= maximumSize_)
    {
      *logofs << "Transport: WARNING! Buffer for FD#" << fd_
              << " grown to reach size of " << newSize
              << " bytes.\n" << logofs_flush;
    }
    #endif

    #ifdef TEST
    *logofs << "Transport: Data buffer for " << "FD#" 
            << fd_ << " has now size " << buffer.data_.size() 
            << " and capacity " << buffer.data_.capacity()
            << ".\n" << logofs_flush;
    #endif
  }

  return (buffer.length_ + size);
}

void Transport::fullReset(T_buffer &buffer)
{
  //
  // Force deallocation and allocation
  // of the initial size.
  //

  #ifdef TEST
  *logofs << "Transport: Resetting buffer for " << "FD#"
          << fd_ << " with size " << buffer.data_.size()
          << " and capacity " << buffer.data_.capacity()
          << ".\n" << logofs_flush;
  #endif

  buffer.start_  = 0;
  buffer.length_ = 0;

  if (buffer.data_.size() > (unsigned int) initialSize_ &&
          buffer.data_.capacity() > (unsigned int) initialSize_)
  {
    buffer.data_.clear();

    buffer.data_.resize(initialSize_);

    #ifdef TEST
    *logofs << "Transport: Data buffer for " << "FD#"
            << fd_ << " shrunk to size " << buffer.data_.size()
            << " and capacity " << buffer.data_.capacity()
            << ".\n" << logofs_flush;
    #endif
  }
}

ProxyTransport::ProxyTransport(int fd) : Transport(fd)
{
  #ifdef TEST
  *logofs << "ProxyTransport: Going to create proxy transport "
          << "for FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  type_ = transport_proxy;

  //
  // Set up the read buffer.
  //

  r_buffer_.length_ = 0;
  r_buffer_.start_  = 0;

  r_buffer_.data_.resize(initialSize_);

  //
  // For now we own the buffer.
  //

  owner_ = 1;

  //
  // Set up ZLIB compression.
  //

  int result;

  r_stream_.zalloc = NULL;
  r_stream_.zfree  = NULL;
  r_stream_.opaque = NULL;

  r_stream_.next_in  = NULL;
  r_stream_.avail_in = 0;

  if ((result = inflateInit2(&r_stream_, 15)) != Z_OK)
  {
    #ifdef PANIC
    *logofs << "ProxyTransport: PANIC! Failed initialization of ZLIB read stream. "
            << "Error is '" << zError(result) << "'.\n" << logofs_flush;
    #endif

    cerr << "Error" << ": Failed initialization of ZLIB read stream. "
         << "Error is '" << zError(result) << "'.\n";

    HandleCleanup();
  }

  if (control -> LocalStreamCompression)
  {
    w_stream_.zalloc = NULL;
    w_stream_.zfree  = NULL;
    w_stream_.opaque = NULL;

    if ((result = deflateInit2(&w_stream_, control -> LocalStreamCompressionLevel, Z_DEFLATED,
                                   15, 9, Z_DEFAULT_STRATEGY)) != Z_OK)
    {
      #ifdef PANIC
      *logofs << "ProxyTransport: PANIC! Failed initialization of ZLIB write stream. "
              << "Error is '" << zError(result) << "'.\n" << logofs_flush;
      #endif

      cerr << "Error" << ": Failed initialization of ZLIB write stream. "
           << "Error is '" << zError(result) << "'.\n";

      HandleCleanup();
    }
  }

  //
  // No ZLIB stream to flush yet.
  //

  flush_ = 0;

  #ifdef REFERENCES
  *logofs << "ProxyTransport: Created new object at " 
          << this << " out of " << ++references_ 
          << " allocated references.\n" << logofs_flush;
  #endif
}

ProxyTransport::~ProxyTransport()
{
  #ifdef TEST
  *logofs << "ProxyTransport: Going to destroy derived class "
          << "for FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  //
  // Deallocate the ZLIB stream state.
  //

  inflateEnd(&r_stream_);

  if (control -> LocalStreamCompression)
  {
    deflateEnd(&w_stream_);
  }

  #ifdef REFERENCES
  *logofs << "ProxyTransport: Deleted object at " 
          << this << " out of " << --references_ 
          << " allocated references.\n" << logofs_flush;
  #endif
}

//
// Read data from its file descriptor.
//

int ProxyTransport::read(unsigned char *data, unsigned int size)
{
  //
  // If the remote peer is not compressing
  // the stream then just return any byte
  // read from the socket.
  //

  if (control -> RemoteStreamCompression == 0)
  {
    int result = Transport::read(data, size);

    if (result <= 0)
    {
      return result;
    }

    statistics -> addBytesIn(result);

    return result;
  }

  //
  // Return any pending data first.
  //

  if (r_buffer_.length_ > 0)
  {
    //
    // If the size of the buffer doesn't
    // match the amount of data pending,
    // force the caller to retry.
    //

    if ((int) size < r_buffer_.length_)
    {
      #ifdef TEST
      *logofs << "ProxyTransport: WARNING! Forcing a retry with "
              << r_buffer_.length_ << " bytes pending and "
              << size << " in the buffer.\n"
              << logofs_flush;
      #endif

      ESET(EAGAIN);

      return -1;
    }

    int copied = (r_buffer_.length_ > ((int) size) ?
                      ((int) size) : r_buffer_.length_);

    memcpy(data, r_buffer_.data_.begin() + r_buffer_.start_, copied);

    //
    // Update the buffer status.
    //

    #ifdef DEBUG
    *logofs << "ProxyTransport: Going to immediately return " << copied
            << " bytes from proxy FD#" << fd_ << ".\n"
            << logofs_flush;
    #endif

    r_buffer_.length_ -= copied;

    if (r_buffer_.length_ == 0)
    {
      r_buffer_.start_ = 0;
    }
    else
    {
      r_buffer_.start_ += copied;

      #ifdef TEST
      *logofs << "ProxyTransport: There are still " << r_buffer_.length_ 
              << " bytes in read buffer for proxy " << "FD#" 
              << fd_ << ".\n" << logofs_flush;
        #endif
    }

    return copied;
  }

  //
  // Read data in the user buffer.
  //

  int result = Transport::read(data, size);

  if (result <= 0)
  {
    return result;
  }

  statistics -> addBytesIn(result);

  //
  // Decompress the data into the read
  // buffer.
  //

  #ifdef DEBUG
  *logofs << "ProxyTransport: Going to decompress data for " 
          << "proxy FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  int saveTotalIn  = r_stream_.total_in;
  int saveTotalOut = r_stream_.total_out;

  int oldTotalIn  = saveTotalIn;
  int oldTotalOut = saveTotalOut;

  int diffTotalIn;
  int diffTotalOut;

  #ifdef INSPECT
  *logofs << "ProxyTransport: oldTotalIn = " << oldTotalIn
          << ".\n" << logofs_flush;
  #endif

  #ifdef INSPECT
  *logofs << "ProxyTransport: oldTotalOut = " << oldTotalOut
          << ".\n" << logofs_flush;
  #endif

  r_stream_.next_in  = (Bytef *) data;
  r_stream_.avail_in = result;

  //
  // Let ZLIB use all the space already
  // available in the buffer.
  //

  unsigned int newAvailOut = r_buffer_.data_.size() - r_buffer_.start_ -
                                 r_buffer_.length_;

  #ifdef TEST
  *logofs << "ProxyTransport: Initial decompress buffer is "
          << newAvailOut << " bytes.\n" << logofs_flush;
  #endif

  for (;;)
  {
    #ifdef INSPECT
    *logofs << "\nProxyTransport: Running the decompress loop.\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_buffer_.length_ = " << r_buffer_.length_
            << ".\n" << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_buffer_.data_.size() = " << r_buffer_.data_.size()
            << ".\n" << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: newAvailOut = " << newAvailOut
            << ".\n" << logofs_flush;
    #endif

    if (resize(r_buffer_, newAvailOut) < 0)
    {
      return -1;
    }

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_buffer_.data_.size() = "
            << r_buffer_.data_.size() << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_stream_.next_in = "
            << (void *) r_stream_.next_in << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_stream_.avail_in = "
            << r_stream_.avail_in << ".\n"
            << logofs_flush;
    #endif

    r_stream_.next_out  = r_buffer_.data_.begin() + r_buffer_.start_ +
                              r_buffer_.length_;

    r_stream_.avail_out = newAvailOut;

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_stream_.next_out = "
            << (void *) r_stream_.next_out << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_stream_.avail_out = "
            << r_stream_.avail_out << ".\n"
            << logofs_flush;
    #endif

    int result = inflate(&r_stream_, Z_SYNC_FLUSH);

    #ifdef INSPECT
    *logofs << "ProxyTransport: Called inflate() result is "
            << result << ".\n" << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_stream_.avail_in = "
            << r_stream_.avail_in << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_stream_.avail_out = "
            << r_stream_.avail_out << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_stream_.total_in = "
            << r_stream_.total_in << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_stream_.total_out = "
            << r_stream_.total_out << ".\n"
            << logofs_flush;
    #endif

    diffTotalIn  = r_stream_.total_in  - oldTotalIn;
    diffTotalOut = r_stream_.total_out - oldTotalOut;

    #ifdef INSPECT
    *logofs << "ProxyTransport: diffTotalIn = "
            << diffTotalIn << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: diffTotalOut = "
            << diffTotalOut << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_buffer_.length_ = "
            << r_buffer_.length_ << ".\n"
            << logofs_flush;
    #endif

    r_buffer_.length_ += diffTotalOut;

    #ifdef INSPECT
    *logofs << "ProxyTransport: r_buffer_.length_ = "
            << r_buffer_.length_ << ".\n"
            << logofs_flush;
    #endif

    oldTotalIn  = r_stream_.total_in;
    oldTotalOut = r_stream_.total_out;

    if (result == Z_OK)
    {
      if (r_stream_.avail_in == 0 && r_stream_.avail_out > 0)
      {
        break;
      }
    }
    else if (result == Z_BUF_ERROR && r_stream_.avail_out > 0 &&
                 r_stream_.avail_in == 0)
    {
      #ifdef TEST
      *logofs << "ProxyTransport: WARNING! Raised Z_BUF_ERROR decompressing data.\n"
              << logofs_flush;
      #endif

      break;
    }
    else
    {
      #ifdef PANIC
      *logofs << "ProxyTransport: PANIC! Decompression of data failed. "
              << "Error is '" << zError(result) << "'.\n"
              << logofs_flush;
      #endif

      cerr << "Error" << ": Decompression of data failed. Error is '"
           << zError(result) << "'.\n";

      finish();

      return -1;
    }

    //
    // Add more bytes to the buffer.
    //

    if (newAvailOut < thresholdSize_)
    {
      newAvailOut = thresholdSize_;
    }

    #ifdef TEST
    *logofs << "ProxyTransport: Need to add " << newAvailOut
            << " bytes to the decompress buffer in read.\n"
            << logofs_flush;
    #endif
  }

  diffTotalIn  = r_stream_.total_in  - saveTotalIn;
  diffTotalOut = r_stream_.total_out - saveTotalOut;

  #ifdef DEBUG
  *logofs << "ProxyTransport: Decompressed data from "
          << diffTotalIn << " to " << diffTotalOut
          << " bytes.\n" << logofs_flush;
  #endif

  statistics -> addDecompressedBytes(diffTotalIn, diffTotalOut);

  //
  // Check if the size of the buffer
  // matches the produced data.
  //

  if ((int) size < r_buffer_.length_)
  {
    #ifdef TEST
    *logofs << "ProxyTransport: WARNING! Forcing a retry with "
            << r_buffer_.length_ << " bytes pending and "
            << size << " in the buffer.\n"
            << logofs_flush;
    #endif

    ESET(EAGAIN);

    return -1;
  }

  //
  // Copy the decompressed data to the
  // provided buffer.
  //

  int copied = (r_buffer_.length_ > ((int) size) ?
                    ((int) size) : r_buffer_.length_);

  #ifdef DEBUG
  *logofs << "ProxyTransport: Going to return " << copied
          << " bytes from proxy FD#" << fd_ << ".\n"
          << logofs_flush;
  #endif

  memcpy(data, r_buffer_.data_.begin() + r_buffer_.start_, copied);

  //
  // Update the buffer status.
  //

  r_buffer_.length_ -= copied;

  if (r_buffer_.length_ == 0)
  {
    r_buffer_.start_ = 0;
  }
  else
  {
    r_buffer_.start_ += copied;

    #ifdef TEST
    *logofs << "ProxyTransport: There are still " << r_buffer_.length_ 
            << " bytes in read buffer for proxy FD#" << fd_
            << ".\n" << logofs_flush;
    #endif
  }

  return copied;
}

//
// If required compress data, else write it to socket.
//

int ProxyTransport::write(T_write type, const unsigned char *data, const unsigned int size)
{
  #ifdef TEST
  if (size == 0)
  {
    *logofs << "ProxyTransport: WARNING! Write called for FD#" 
            << fd_ << " without any data to write.\n"
            << logofs_flush;

    return 0;
  }
  #endif

  //
  // If there is no compression revert to
  // plain socket management.
  //

  if (control -> LocalStreamCompression == 0)
  {
    int result = Transport::write(type, data, size);

    if (result <= 0)
    {
      return result;
    }

    statistics -> addBytesOut(result);

    statistics -> updateBitrate(result);

    FlushCallback(result);

    return result;
  }

  #ifdef DEBUG
  *logofs << "ProxyTransport: Going to compress " << size 
          << " bytes to write buffer for proxy FD#" << fd_
          << ".\n" << logofs_flush;
  #endif

  //
  // Compress data into the write buffer.
  //

  int saveTotalIn  = w_stream_.total_in;
  int saveTotalOut = w_stream_.total_out;

  int oldTotalIn  = saveTotalIn;
  int oldTotalOut = saveTotalOut;

  int diffTotalIn;
  int diffTotalOut;

  #ifdef INSPECT
  *logofs << "ProxyTransport: oldTotalIn = " << oldTotalIn
          << ".\n" << logofs_flush;
  #endif

  #ifdef INSPECT
  *logofs << "ProxyTransport: oldTotalOut = " << oldTotalOut
          << ".\n" << logofs_flush;
  #endif

  w_stream_.next_in  = (Bytef *) data;
  w_stream_.avail_in = size;

  //
  // Let ZLIB use all the space already
  // available in the buffer.
  //

  unsigned int newAvailOut = w_buffer_.data_.size() - w_buffer_.start_ -
                                 w_buffer_.length_;

  #ifdef TEST
  *logofs << "ProxyTransport: Initial compress buffer is "
          << newAvailOut << " bytes.\n" << logofs_flush;
  #endif

  for (;;)
  {
    #ifdef INSPECT
    *logofs << "\nProxyTransport: Running the compress loop.\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_buffer_.length_ = "
            << w_buffer_.length_ << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_buffer_.data_.size() = "
            << w_buffer_.data_.size() << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: newAvailOut = "
            << newAvailOut << ".\n"
            << logofs_flush;
    #endif

    if (resize(w_buffer_, newAvailOut) < 0)
    {
      return -1;
    }

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_buffer_.data_.size() = "
            << w_buffer_.data_.size() << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.next_in = "
            << (void *) w_stream_.next_in << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.avail_in = "
            << w_stream_.avail_in << ".\n"
            << logofs_flush;
    #endif

    w_stream_.next_out  = w_buffer_.data_.begin() + w_buffer_.start_ +
                              w_buffer_.length_;

    w_stream_.avail_out = newAvailOut;

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.next_out = "
            << (void *) w_stream_.next_out << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.avail_out = "
            << w_stream_.avail_out << ".\n"
            << logofs_flush;
    #endif

    int result = deflate(&w_stream_, (type == write_delayed ?
                             Z_NO_FLUSH : Z_SYNC_FLUSH));

    #ifdef INSPECT
    *logofs << "ProxyTransport: Called deflate() result is "
            << result << ".\n" << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.avail_in = "
            << w_stream_.avail_in << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.avail_out = "
            << w_stream_.avail_out << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.total_in = "
            << w_stream_.total_in << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.total_out = "
            << w_stream_.total_out << ".\n"
            << logofs_flush;
    #endif

    diffTotalOut = w_stream_.total_out - oldTotalOut;
    diffTotalIn  = w_stream_.total_in  - oldTotalIn;

    #ifdef INSPECT
    *logofs << "ProxyTransport: diffTotalIn = "
            << diffTotalIn << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: diffTotalOut = "
            << diffTotalOut << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_buffer_.length_ = "
            << w_buffer_.length_ << ".\n"
            << logofs_flush;
    #endif

    w_buffer_.length_ += diffTotalOut;

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_buffer_.length_ = "
            << w_buffer_.length_ << ".\n"
            << logofs_flush;
    #endif

    oldTotalOut = w_stream_.total_out;
    oldTotalIn  = w_stream_.total_in;

    if (result == Z_OK)
    {
      if (w_stream_.avail_in == 0 && w_stream_.avail_out > 0)
      {
        break;
      }
    }
    else if (result == Z_BUF_ERROR && w_stream_.avail_out > 0 &&
                 w_stream_.avail_in == 0)
    {
      #ifdef TEST
      *logofs << "ProxyTransport: WARNING! Raised Z_BUF_ERROR compressing data.\n"
              << logofs_flush;
      #endif

      break;
    }
    else
    {
      #ifdef PANIC
      *logofs << "ProxyTransport: PANIC! Compression of data failed. "
              << "Error is '" << zError(result) << "'.\n"
              << logofs_flush;
      #endif

      cerr << "Error" << ": Compression of data failed. Error is '"
           << zError(result) << "'.\n";

      finish();

      return -1;
    }

    //
    // Add more bytes to the buffer.
    //

    if (newAvailOut < thresholdSize_)
    {
      newAvailOut = thresholdSize_;
    }

    #ifdef TEST
    *logofs << "ProxyTransport: Need to add " << newAvailOut
            << " bytes to the compress buffer in write.\n"
            << logofs_flush;
    #endif
  }

  diffTotalIn  = w_stream_.total_in  - saveTotalIn;
  diffTotalOut = w_stream_.total_out - saveTotalOut;

  #ifdef TEST

  *logofs << "ProxyTransport: Compressed data from "
          << diffTotalIn << " to " << diffTotalOut
          << " bytes.\n" << logofs_flush;

  if (diffTotalIn != (int) size)
  {
    #ifdef PANIC
    *logofs << "ProxyTransport: PANIC! Bytes provided to ZLIB stream "
            << "should be " << size << " but they look to be "
            << diffTotalIn << ".\n" << logofs_flush;
    #endif
  }

  #endif

  //
  // Find out what we have to do with the
  // produced data.
  //

  if (type == write_immediate)
  {
    //
    // If user requested an immediate write we
    // flushed the ZLIB buffer. We can now reset
    // the counter and write data to socket.
    //

    flush_ = 0;

    #ifdef TEST
    *logofs << "ProxyTransport: Write buffer for proxy FD#" << fd_
            << " has data for " << w_buffer_.length_ << " bytes.\n"
            << logofs_flush;

    *logofs << "ProxyTransport: Start is " << w_buffer_.start_ 
            << " length is " << w_buffer_.length_ << " flush is "
            << flush_ << " size is " << w_buffer_.data_.size()
            << " capacity is " << w_buffer_.data_.capacity()
            << ".\n" << logofs_flush;
    #endif

    //
    // Alternatively may try to write only if
    // the socket is not blocked.
    //
    // if (w_buffer_.length_ > 0 && blocked_ == 0)
    // {
    //   ...
    // }
    //

    if (w_buffer_.length_ > 0)

    {
      #ifdef TEST
      *logofs << "ProxyTransport: Writing " << w_buffer_.length_
              << " bytes of produced data to FD#" << fd_ << ".\n"
              << logofs_flush;
      #endif

      int result = Transport::flush();

      if (result < 0)
      {
        return -1;
      }
    }
  }
  else
  {
    //
    // We haven't flushed the ZLIB compression
    // buffer, so user will have to call proxy
    // transport's flush explicitly.
    //

    flush_ += diffTotalIn;
  }

  //
  // We either wrote the data or added it to the
  // write buffer. It's convenient to update the
  // counters at this stage to get the current
  // bitrate earlier.
  //

  statistics -> addCompressedBytes(diffTotalIn, diffTotalOut);

  statistics -> addBytesOut(diffTotalOut);

  statistics -> updateBitrate(diffTotalOut);

  FlushCallback(diffTotalOut);

  #ifdef TEST
  *logofs << "ProxyTransport: Write buffer for proxy FD#" << fd_
          << " has data for " << w_buffer_.length_ << " bytes.\n"
          << logofs_flush;

  *logofs << "ProxyTransport: Start is " << w_buffer_.start_ 
          << " length is " << w_buffer_.length_ << " flush is "
          << flush_ << " size is " << w_buffer_.data_.size()
          << " capacity is " << w_buffer_.data_.capacity()
          << ".\n" << logofs_flush;
  #endif

  return size;
}

//
// Write data to its file descriptor.
//

int ProxyTransport::flush()
{
  //
  // If there is no compression or we already compressed
  // outgoing data and just need to write it to socket
  // because of previous incomplete writes then revert
  // to plain socket management.
  //

  if (flush_ == 0 || control -> LocalStreamCompression == 0)
  {
    int result = Transport::flush();

    if (result < 0)
    {
      return -1;
    }

    return result;
  }

  #ifdef DEBUG
  *logofs << "ProxyTransport: Going to flush compression on "
          << "proxy FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  #ifdef TEST
  *logofs << "ProxyTransport: Flush counter for proxy FD#" << fd_
          << " is " << flush_ << " bytes.\n" << logofs_flush;
  #endif

  //
  // Flush ZLIB stream into the write buffer.
  //

  int saveTotalIn  = w_stream_.total_in;
  int saveTotalOut = w_stream_.total_out;

  int oldTotalIn  = saveTotalIn;
  int oldTotalOut = saveTotalOut;

  int diffTotalOut;
  int diffTotalIn;

  #ifdef INSPECT
  *logofs << "ProxyTransport: oldTotalIn = " << oldTotalIn
          << ".\n" << logofs_flush;
  #endif

  #ifdef INSPECT
  *logofs << "ProxyTransport: oldTotalOut = " << oldTotalOut
          << ".\n" << logofs_flush;
  #endif

  w_stream_.next_in  = w_buffer_.data_.begin() + w_buffer_.start_ + w_buffer_.length_;
  w_stream_.avail_in = 0;

  //
  // Let ZLIB use all the space already
  // available in the buffer.
  //

  unsigned int newAvailOut = w_buffer_.data_.size() - w_buffer_.start_ -
                                 w_buffer_.length_;

  #ifdef DEBUG
  *logofs << "ProxyTransport: Initial flush buffer is "
          << newAvailOut << " bytes.\n" << logofs_flush;
  #endif

  for (;;)
  {
    #ifdef INSPECT
    *logofs << "\nProxyTransport: Running the flush loop.\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_buffer_.length_ = "
            << w_buffer_.length_ << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_buffer_.data_.size() = "
            << w_buffer_.data_.size() << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: newAvailOut = "
            << newAvailOut << ".\n"
            << logofs_flush;
    #endif

    if (resize(w_buffer_, newAvailOut) < 0)
    {
      return -1;
    }

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_buffer_.data_.size() = "
            << w_buffer_.data_.size() << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.next_in = "
            << (void *) w_stream_.next_in << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.avail_in = "
            << w_stream_.avail_in << ".\n"
            << logofs_flush;
    #endif

    w_stream_.next_out  = w_buffer_.data_.begin() + w_buffer_.start_ +
                              w_buffer_.length_;

    w_stream_.avail_out = newAvailOut;

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.next_out = "
            << (void *) w_stream_.next_out << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.avail_out = "
            << w_stream_.avail_out << ".\n"
            << logofs_flush;
    #endif

    int result = deflate(&w_stream_, Z_SYNC_FLUSH);

    #ifdef INSPECT
    *logofs << "ProxyTransport: Called deflate() result is "
            << result << ".\n" << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.avail_in = "
            << w_stream_.avail_in << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.avail_out = "
            << w_stream_.avail_out << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.total_in = "
            << w_stream_.total_in << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_stream_.total_out = "
            << w_stream_.total_out << ".\n"
            << logofs_flush;
    #endif

    diffTotalOut = w_stream_.total_out - oldTotalOut;
    diffTotalIn  = w_stream_.total_in  - oldTotalIn;

    #ifdef INSPECT
    *logofs << "ProxyTransport: diffTotalIn = "
            << diffTotalIn << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: diffTotalOut = "
            << diffTotalOut << ".\n"
            << logofs_flush;
    #endif

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_buffer_.length_ = "
            << w_buffer_.length_ << ".\n"
            << logofs_flush;
    #endif

    w_buffer_.length_ += diffTotalOut;

    #ifdef INSPECT
    *logofs << "ProxyTransport: w_buffer_.length_ = "
            << w_buffer_.length_ << ".\n"
            << logofs_flush;
    #endif

    oldTotalOut = w_stream_.total_out;
    oldTotalIn  = w_stream_.total_in;

    if (result == Z_OK)
    {
      if (w_stream_.avail_in == 0 && w_stream_.avail_out > 0)
      {
        break;
      }
    }
    else if (result == Z_BUF_ERROR && w_stream_.avail_out > 0 &&
                 w_stream_.avail_in == 0)
    {
      #ifdef TEST
      *logofs << "ProxyTransport: WARNING! Raised Z_BUF_ERROR flushing data.\n"
              << logofs_flush;
      #endif

      break;
    }
    else
    {
      #ifdef PANIC
      *logofs << "ProxyTransport: PANIC! Flush of compressed data failed. "
              << "Error is '" << zError(result) << "'.\n"
              << logofs_flush;
      #endif

      cerr << "Error" << ": Flush of compressed data failed. Error is '"
           << zError(result) << "'.\n";

      finish();

      return -1;
    }

    //
    // Add more bytes to the buffer.
    //

    if (newAvailOut < thresholdSize_)
    {
      newAvailOut = thresholdSize_;
    }

    #ifdef TEST
    *logofs << "ProxyTransport: Need to add " << newAvailOut
            << " bytes to the compress buffer in flush.\n"
            << logofs_flush;
    #endif
  }

  diffTotalIn  = w_stream_.total_in  - saveTotalIn;
  diffTotalOut = w_stream_.total_out - saveTotalOut;

  #ifdef TEST
  *logofs << "ProxyTransport: Compressed flush data from "
          << diffTotalIn << " to " << diffTotalOut
          << " bytes.\n" << logofs_flush;
  #endif

  //
  // Time to move data from the write
  // buffer to the real link. 
  //

  #ifdef DEBUG
  *logofs << "ProxyTransport: Reset flush counter for proxy FD#"
          << fd_ << ".\n" << logofs_flush;
  #endif

  flush_ = 0;

  #ifdef TEST
  *logofs << "ProxyTransport: Write buffer for proxy FD#" << fd_
          << " has data for " << w_buffer_.length_ << " bytes.\n"
          << logofs_flush;

  *logofs << "ProxyTransport: Start is " << w_buffer_.start_ 
          << " length is " << w_buffer_.length_ << " flush is "
          << flush_ << " size is " << w_buffer_.data_.size()
          << " capacity is " << w_buffer_.data_.capacity()
          << ".\n" << logofs_flush;
  #endif

  int result = Transport::flush();

  if (result < 0)
  {
    return -1;
  }

  //
  // Update all the counters.
  //

  statistics -> addCompressedBytes(diffTotalIn, diffTotalOut);

  statistics -> addBytesOut(diffTotalOut);

  statistics -> updateBitrate(diffTotalOut);

  FlushCallback(diffTotalOut);

  return result;
}

unsigned int ProxyTransport::getPending(unsigned char *&data)
{
  //
  // Return a pointer to the data in the
  // read buffer. It is up to the caller
  // to ensure that the data is consumed
  // before the read buffer is reused.
  //

  if (r_buffer_.length_ > 0)
  {
    unsigned int size = r_buffer_.length_;

    data = r_buffer_.data_.begin() + r_buffer_.start_;

    #ifdef DEBUG
    *logofs << "ProxyTransport: Returning " << size
            << " pending bytes from proxy FD#" << fd_
            << ".\n" << logofs_flush;
    #endif

    r_buffer_.length_ = 0;
    r_buffer_.start_  = 0;

    //
    // Prevent the deletion of the buffer.
    //

    owner_ = 0;

    return size;
  }

  #ifdef TEST
  *logofs << "ProxyTransport: WARNING! No pending data "
          << "for proxy FD#" << fd_ << ".\n"
          << logofs_flush;
  #endif

  data = NULL;

  return 0;
}

void ProxyTransport::fullReset()
{
  blocked_ = 0;
  finish_  = 0;
  flush_   = 0;

  if (control -> RemoteStreamCompression)
  {
    inflateReset(&r_stream_);
  }

  if (control -> LocalStreamCompression)
  {
    deflateReset(&w_stream_);
  }

  if (owner_ == 1)
  {
    Transport::fullReset(r_buffer_);
  }

  Transport::fullReset(w_buffer_);
}

AgentTransport::AgentTransport(int fd) : Transport(fd)
{
  #ifdef TEST
  *logofs << "AgentTransport: Going to create agent transport "
          << "for FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  type_ = transport_agent;

  //
  // Set up the read buffer.
  //

  r_buffer_.length_ = 0;
  r_buffer_.start_  = 0;

  r_buffer_.data_.resize(initialSize_);

  //
  // For now we own the buffer.
  //

  owner_ = 1;

  //
  // Set up the mutexes.
  //

  #ifdef THREADS

  pthread_mutexattr_t m_attributes;

  pthread_mutexattr_init(&m_attributes);

  //
  // Interfaces in pthread to handle mutex
  // type do not work in current version. 
  //

  m_attributes.__mutexkind = PTHREAD_MUTEX_ERRORCHECK_NP;

  if (pthread_mutex_init(&m_read_, &m_attributes) != 0)
  {
    #ifdef TEST
    *logofs << "AgentTransport: Child: Creation of read mutex failed. "
            << "Error is " << EGET() << " '" << ESTR()
            << "'.\n" << logofs_flush;
    #endif
  }

  if (pthread_mutex_init(&m_write_, &m_attributes) != 0)
  {
    #ifdef TEST
    *logofs << "AgentTransport: Child: Creation of write mutex failed. "
            << "Error is " << EGET() << " '" << ESTR()
            << "'.\n" << logofs_flush;
    #endif
  }

  #endif

  #ifdef REFERENCES
  *logofs << "AgentTransport: Child: Created new object at " 
          << this << " out of " << ++references_ 
          << " allocated references.\n" << logofs_flush;
  #endif
}

AgentTransport::~AgentTransport()
{
  #ifdef TEST
  *logofs << "AgentTransport: Going to destroy derived class "
          << "for FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  //
  // Unlock and free all mutexes.
  //

  #ifdef THREADS

  pthread_mutex_unlock(&m_read_);
  pthread_mutex_unlock(&m_write_);

  pthread_mutex_destroy(&m_read_);
  pthread_mutex_destroy(&m_write_);

  #endif

  #ifdef REFERENCES
  *logofs << "AgentTransport: Child: Deleted object at " 
          << this << " out of " << --references_ 
          << " allocated references.\n" << logofs_flush;
  #endif
}

//
// Read data enqueued by the other thread.
//

int AgentTransport::read(unsigned char *data, unsigned int size)
{
  #ifdef THREADS

  lockRead();

  #endif

  #ifdef DEBUG
  *logofs << "AgentTransport: Child: Going to read " << size
          << " bytes from " << "FD#" << fd_ << ".\n"
          << logofs_flush;
  #endif

  int copied = -1;

  if (r_buffer_.length_ > 0)
  {
    if ((int) size < r_buffer_.length_)
    {
      #ifdef TEST
      *logofs << "AgentTransport: WARNING! Forcing a retry with "
              << r_buffer_.length_ << " bytes pending and "
              << size << " in the buffer.\n"
              << logofs_flush;
      #endif

      ESET(EAGAIN);
    }
    else
    {
      copied = (r_buffer_.length_ > ((int) size) ?
                    ((int) size) : r_buffer_.length_);

      memcpy(data, r_buffer_.data_.begin() + r_buffer_.start_, copied);

      //
      // Update the buffer status.
      //

      #ifdef TEST
      *logofs << "AgentTransport: Child: Going to immediately return "
              << copied << " bytes from FD#" << fd_ << ".\n"
              << logofs_flush;
      #endif

      #ifdef DUMP

      *logofs << "AgentTransport: Child: Dumping content of read data.\n"
              << logofs_flush;

      DumpData(data, copied);

      #endif

      r_buffer_.length_ -= copied;

      if (r_buffer_.length_ == 0)
      {
        r_buffer_.start_ = 0;
      }
      else
      {
        r_buffer_.start_ += copied;

        #ifdef TEST
        *logofs << "AgentTransport: Child: There are still "
                << r_buffer_.length_  << " bytes in read buffer for "
                << "FD#" << fd_ << ".\n" << logofs_flush;
        #endif
      }
    }
  }
  else
  {
    #ifdef DEBUG
    *logofs << "AgentTransport: Child: No data can be got "
            << "from read buffer for FD#" << fd_ << ".\n"
            << logofs_flush;
    #endif

    ESET(EAGAIN);
  }

  #ifdef THREADS

  unlockRead();

  #endif

  return copied;
}

//
// Write data to buffer so that the other
// thread can get it.
//

int AgentTransport::write(T_write type, const unsigned char *data, const unsigned int size)
{
  #ifdef THREADS

  lockWrite();

  #endif

  //
  // Just append data to socket's write buffer.
  // Note that we don't care if buffer exceeds
  // the size limits set for this type of
  // transport.
  //

  #ifdef TEST
  *logofs << "AgentTransport: Child: Going to append " << size
          << " bytes to write buffer for " << "FD#" << fd_
          << ".\n" << logofs_flush;
  #endif

  int copied = -1;

  if (resize(w_buffer_, size) < 0)
  {
    finish();

    ESET(EPIPE);
  }
  else
  {
    memmove(w_buffer_.data_.begin() + w_buffer_.start_ + w_buffer_.length_, data, size);

    w_buffer_.length_ += size;

    #ifdef DUMP

    *logofs << "AgentTransport: Child: Dumping content of written data.\n"
            << logofs_flush;

    DumpData(data, size);

    #endif

    #ifdef TEST
    *logofs << "AgentTransport: Child: Write buffer for FD#" << fd_
            << " has data for " << w_buffer_.length_ << " bytes.\n"
            << logofs_flush;

    *logofs << "AgentTransport: Child: Start is " << w_buffer_.start_ 
            << " length is " << w_buffer_.length_ << " size is "
            << w_buffer_.data_.size() << " capacity is "
            << w_buffer_.data_.capacity() << ".\n"
            << logofs_flush;
    #endif

    copied = size;
  }

  //
  // Let child access again the read buffer.
  //

  #ifdef THREADS

  unlockWrite();

  #endif

  return copied;
}

int AgentTransport::flush()
{
  //
  // In case of memory-to-memory transport
  // this function should never be called.
  //

  #ifdef PANIC
  *logofs << "AgentTransport: Child: PANIC! Called flush() for "
          << "memory to memory transport on " << "FD#"
          << fd_ << ".\n" << logofs_flush;
  #endif

  cerr << "Error" << ": Called flush() for "
       << "memory to memory transport on " << "FD#"
       << fd_ << ".\n";

  HandleAbort();
}

int AgentTransport::drain(int limit, int timeout)
{
  //
  // We can't drain the channel in the case
  // of the memory-to-memory transport. Data
  // is enqueued for the agent to read but
  // the agent could require multiple loops
  // to read it all.
  //

  //
  // In case of memory-to-memory transport
  // this function should never be called.
  //

  #ifdef PANIC
  *logofs << "AgentTransport: Child: PANIC! Called drain() for "
          << "memory to memory transport on " << "FD#"
          << fd_ << ".\n" << logofs_flush;
  #endif

  cerr << "Error" << ": Called drain() for "
       << "memory to memory transport on " << "FD#"
       << fd_ << ".\n";

  HandleAbort();
}

unsigned int AgentTransport::getPending(unsigned char *&data)
{
  #ifdef THREADS

  lockRead();

  #endif

  if (r_buffer_.length_ > 0)
  {
    unsigned int size = r_buffer_.length_;

    data = r_buffer_.data_.begin() + r_buffer_.start_;

    #ifdef DEBUG
    *logofs << "AgentTransport: Child: Returning " << size
            << " pending bytes from FD#" << fd_
            << ".\n" << logofs_flush;
    #endif

    r_buffer_.length_ = 0;
    r_buffer_.start_  = 0;

    #ifdef THREADS

    unlockRead();

    #endif

    //
    // Prevent the deletion of the buffer.
    //

    owner_ = 0;

    return size;
  }

  #ifdef TEST
  *logofs << "AgentTransport: WARNING! No pending data "
          << "for FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  #ifdef THREADS

  unlockRead();

  #endif

  data = NULL;

  return 0;
}

void AgentTransport::fullReset()
{
  #ifdef THREADS

  lockRead();
  lockWrite();

  #endif

  #ifdef TEST
  *logofs << "AgentTransport: Child: Resetting transport "
          << "for FD#" << fd_ << ".\n" << logofs_flush;
  #endif

  blocked_ = 0;
  finish_  = 0;

  if (owner_ == 1)
  {
    Transport::fullReset(r_buffer_);
  }

  Transport::fullReset(w_buffer_);
}

int AgentTransport::enqueue(const char *data, const int size)
{
  #ifdef THREADS

  lockRead();

  #endif

  if (finish_ == 1)
  {
    #if defined(PARENT) && defined(TEST)
    *logofs << "AgentTransport: Parent: Returning EPIPE in "
            << "write for finishing FD#" << fd_ << ".\n"
           << logofs_flush;
    #endif

    ESET(EPIPE);

    return -1;
  }

  //
  // Always allow the agent to write
  // all its data.
  //

  int toPut = size;

  #if defined(PARENT) && defined(TEST)
  *logofs << "AgentTransport: Parent: Going to put " << toPut
          << " bytes into read buffer for FD#" << fd_
          << ". Buffer length is " << r_buffer_.length_
          << ".\n" << logofs_flush;
  #endif

  if (resize(r_buffer_, toPut) < 0)
  {
    finish();

    #ifdef THREADS

    unlockRead();

    #endif

    return -1;
  }

  memcpy(r_buffer_.data_.begin() + r_buffer_.start_ + r_buffer_.length_, data, toPut);

  r_buffer_.length_ += toPut;

  #if defined(DUMP) && defined(PARENT)

  *logofs << "AgentTransport: Parent: Dumping content of enqueued data.\n"
          << logofs_flush;

  DumpData((const unsigned char *) data, toPut);

  #endif

  #if defined(PARENT) && defined(TEST)
  *logofs << "AgentTransport: Parent: Read buffer for FD#" << fd_
          << " has now data for " << r_buffer_.length_
          << " bytes.\n" << logofs_flush;

  *logofs << "AgentTransport: Parent: Start is " << r_buffer_.start_ 
          << " length is " << r_buffer_.length_ << " size is "
          << r_buffer_.data_.size() << " capacity is "
          << r_buffer_.data_.capacity() << ".\n"
          << logofs_flush;
  #endif

  #ifdef THREADS

  unlockRead();

  #endif

  return toPut;
}

int AgentTransport::dequeue(char *data, int size)
{
  #ifdef THREADS

  lockWrite();

  #endif

  if (w_buffer_.length_ == 0)
  {
    if (finish_ == 1)
    {
      #if defined(PARENT) && defined(TEST)
      *logofs << "AgentTransport: Parent: Returning 0 in read "
              << "for finishing FD#" << fd_ << ".\n"
              << logofs_flush;
      #endif

      return 0;
    }

    #if defined(PARENT) && defined(TEST)
    *logofs << "AgentTransport: Parent: No data can be read "
            << "from write buffer for FD#" << fd_ << ".\n"
            << logofs_flush;
    #endif

    ESET(EAGAIN);

    #ifdef THREADS

    unlockWrite();

    #endif

    return -1;
  }

  //
  // Return as many bytes as possible.
  //

  int toGet = ((int) size > w_buffer_.length_ ? w_buffer_.length_ : size);

  #if defined(PARENT) && defined(TEST)
  *logofs << "AgentTransport: Parent: Going to get " << toGet
          << " bytes from write buffer for FD#" << fd_ << ".\n"
          << logofs_flush;
  #endif

  memcpy(data, w_buffer_.data_.begin() + w_buffer_.start_, toGet);

  w_buffer_.start_  += toGet;
  w_buffer_.length_ -= toGet;

  #if defined(DUMP) && defined(PARENT)

  *logofs << "AgentTransport: Parent: Dumping content of dequeued data.\n"
          << logofs_flush;

  DumpData((const unsigned char *) data, toGet);

  #endif

  #if defined(PARENT) && defined(TEST)
  *logofs << "AgentTransport: Parent: Write buffer for FD#" << fd_
          << " has now data for " << length() << " bytes.\n"
          << logofs_flush;

  *logofs << "AgentTransport: Parent: Start is " << w_buffer_.start_ 
          << " length is " << w_buffer_.length_ << " size is "
          << w_buffer_.data_.size() << " capacity is "
          << w_buffer_.data_.capacity() << ".\n"
          << logofs_flush;
  #endif

  #ifdef THREADS

  unlockWrite();

  #endif

  return toGet;
}

int AgentTransport::dequeuable()
{
  if (finish_ == 1)
  {
    #if defined(PARENT) && defined(TEST)
    *logofs << "AgentTransport: Parent: Returning EPIPE in "
            << "readable for finishing FD#" << fd_
            << ".\n" << logofs_flush;
    #endif

    ESET(EPIPE);

    return -1;
  }

  #if defined(PARENT) && defined(TEST)
  *logofs << "AgentTransport: Parent: Returning "
          << w_buffer_.length_ << " as data readable "
          << "from read buffer for FD#" << fd_ << ".\n"
          << logofs_flush;
  #endif

  return w_buffer_.length_;
}

#ifdef THREADS

int AgentTransport::lockRead()
{
  for (;;)
  {
    int result = pthread_mutex_lock(&m_read_);

    if (result == 0)
    {
      #ifdef DEBUG
      *logofs << "AgentTransport: Read mutex locked by thread id "
              << pthread_self() << ".\n" << logofs_flush;
      #endif

      return 0;
    }
    else if (EGET() == EINTR)
    {
      continue;
    }
    else
    {
      #ifdef WARNING
      *logofs << "AgentTransport: WARNING! Locking of read mutex by thread id "
              << pthread_self() << " returned " << result << ". Error is '"
              << ESTR() << "'.\n" << logofs_flush;
      #endif

      return result;
    }
  }
}

int AgentTransport::lockWrite()
{
  for (;;)
  {
    int result = pthread_mutex_lock(&m_write_);

    if (result == 0)
    {
      #ifdef DEBUG
      *logofs << "AgentTransport: Write mutex locked by thread id "
              << pthread_self() << ".\n" << logofs_flush;
      #endif

      return 0;
    }
    else if (EGET() == EINTR)
    {
      continue;
    }
    else
    {
      #ifdef WARNING
      *logofs << "AgentTransport: WARNING! Locking of write mutex by thread id "
              << pthread_self() << " returned " << result << ". Error is '"
              << ESTR() << "'.\n" << logofs_flush;
      #endif

      return result;
    }
  }
}

int AgentTransport::unlockRead()
{
  for (;;)
  {
    int result = pthread_mutex_unlock(&m_read_);

    if (result == 0)
    {
      #ifdef DEBUG
      *logofs << "AgentTransport: Read mutex unlocked by thread id "
              << pthread_self() << ".\n" << logofs_flush;
      #endif

      return 0;
    }
    else if (EGET() == EINTR)
    {
      continue;
    }
    else
    {
      #ifdef WARNING
      *logofs << "AgentTransport: WARNING! Unlocking of read mutex by thread id "
              << pthread_self() << " returned " << result << ". Error is '"
              << ESTR() << "'.\n" << logofs_flush;
      #endif

      return result;
    }
  }
}

int AgentTransport::unlockWrite()
{
  for (;;)
  {
    int result = pthread_mutex_unlock(&m_write_);

    if (result == 0)
    {
      #ifdef DEBUG
      *logofs << "AgentTransport: Write mutex unlocked by thread id "
              << pthread_self() << ".\n" << logofs_flush;
      #endif

      return 0;
    }
    else if (EGET() == EINTR)
    {
      continue;
    }
    else
    {
      #ifdef WARNING
      *logofs << "AgentTransport: WARNING! Unlocking of write mutex by thread id "
              << pthread_self() << " returned " << result << ". Error is '"
              << ESTR() << "'.\n" << logofs_flush;
      #endif

      return result;
    }
  }
}

#endif