aboutsummaryrefslogtreecommitdiff
path: root/src/stream/stream_api.c
blob: b4a47b53d4152f46d5cdae840ff7634831a5bccd (plain) (blame)
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
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
/*
  This file is part of GNUnet.
  (C) 2008--2013 Christian Grothoff (and other contributing authors)

  GNUnet is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
  by the Free Software Foundation; either version 3, or (at your
  option) any later version.

  GNUnet is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with GNUnet; see the file COPYING.  If not, write to the
  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.
*/

/* TODO:
 *
 * Checks for matching the sender and socket->other_peer in server
 * message handlers  
 *
 * Add code for write io timeout
 *
 * Include retransmission for control messages
 **/

/**
 * @file stream/stream_api.c
 * @brief Implementation of the stream library
 * @author Sree Harsha Totakura
 */

#include "platform.h"
#include "gnunet_common.h"
#include "gnunet_util_lib.h"
#include "gnunet_lockmanager_service.h"
#include "gnunet_statistics_service.h"
#include "gnunet_stream_lib.h"
#include "stream.h"

/**
 * Generic logging shorthand
 */
#define LOG(kind,...)                                   \
  GNUNET_log_from (kind, "stream-api", __VA_ARGS__)

/**
 * Debug logging shorthand
 */
#define LOG_DEBUG(...)                          \
  LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)

/**
 * Time in relative seconds shorthand
 */
#define TIME_REL_SECS(sec) \
  GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, sec)

/**
 * The maximum packet size of a stream packet
 */
#define DEFAULT_MAX_PAYLOAD_SIZE 64000

/**
 * Receive buffer
 */
#define RECEIVE_BUFFER_SIZE 4096000

/**
 * states in the Protocol
 */
enum State
  {
    /**
     * Client initialization state
     */
    STATE_INIT,

    /**
     * Listener initialization state 
     */
    STATE_LISTEN,

    /**
     * Pre-connection establishment state
     */
    STATE_HELLO_WAIT,

    /**
     * State where a connection has been established
     */
    STATE_ESTABLISHED,

    /**
     * State where the socket is closed on our side and waiting to be ACK'ed
     */
    STATE_RECEIVE_CLOSE_WAIT,

    /**
     * State where the socket is closed for reading
     */
    STATE_RECEIVE_CLOSED,

    /**
     * State where the socket is closed on our side and waiting to be ACK'ed
     */
    STATE_TRANSMIT_CLOSE_WAIT,

    /**
     * State where the socket is closed for writing
     */
    STATE_TRANSMIT_CLOSED,

    /**
     * State where the socket is closed on our side and waiting to be ACK'ed
     */
    STATE_CLOSE_WAIT,

    /**
     * State where the socket is closed
     */
    STATE_CLOSED 
  };


/**
 * Functions of this type are called when a message is written
 *
 * @param cls the closure from queue_message
 * @param socket the socket the written message was bound to
 */
typedef void (*SendFinishCallback) (void *cls,
                                    struct GNUNET_STREAM_Socket *socket);


/**
 * The send message queue
 */
struct MessageQueue
{
  /**
   * The message
   */
  struct GNUNET_MessageHeader *message;

  /**
   * Callback to be called when the message is sent
   */
  SendFinishCallback finish_cb;

  /**
   * The closure for finish_cb
   */
  void *finish_cb_cls;

  /**
   * The next message in queue. Should be NULL in the last message
   */
  struct MessageQueue *next;

  /**
   * The next message in queue. Should be NULL in the first message
   */
  struct MessageQueue *prev;
};


/**
 * The STREAM Socket Handler
 */
struct GNUNET_STREAM_Socket
{
  /**
   * The mesh handle
   */
  struct GNUNET_MESH_Handle *mesh;

  /**
   * Handle to statistics
   */
  struct GNUNET_STATISTICS_Handle *stat_handle;

  /**
   * The mesh tunnel handle
   */
  struct GNUNET_MESH_Tunnel *tunnel;

  /**
   * Stream open closure
   */
  void *open_cls;

  /**
   * Stream open callback
   */
  GNUNET_STREAM_OpenCallback open_cb;

  /**
   * The current transmit handle (if a pending transmit request exists)
   */
  struct GNUNET_MESH_TransmitHandle *transmit_handle;

  /**
   * The current message associated with the transmit handle
   */
  struct MessageQueue *queue_head;

  /**
   * The queue tail, should always point to the last message in queue
   */
  struct MessageQueue *queue_tail;

  /**
   * The write IO_handle associated with this socket
   */
  struct GNUNET_STREAM_WriteHandle *write_handle;

  /**
   * The read IO_handle associated with this socket
   */
  struct GNUNET_STREAM_ReadHandle *read_handle;

  /**
   * The shutdown handle associated with this socket
   */
  struct GNUNET_STREAM_ShutdownHandle *shutdown_handle;

  /**
   * Buffer for storing received messages
   */
  void *receive_buffer;

  /**
   * The listen socket from which this socket is derived. Should be NULL if it
   * is not a derived socket
   */
  struct GNUNET_STREAM_ListenSocket *lsocket;

  /**
   * The peer identity of the peer at the other end of the stream
   */
  struct GNUNET_PeerIdentity other_peer;

  /**
   * The Acknowledgement Bitmap
   */
  GNUNET_STREAM_AckBitmap ack_bitmap;

  /**
   * Task identifier for retransmission task after timeout
   */
  GNUNET_SCHEDULER_TaskIdentifier data_retransmission_task_id;

  /**
   * Task identifier for retransmission of control messages
   */
  GNUNET_SCHEDULER_TaskIdentifier control_retransmission_task_id;

  /**
   * The task for sending timely Acks
   */
  GNUNET_SCHEDULER_TaskIdentifier ack_task_id;

  /**
   * Retransmission timeout
   */
  struct GNUNET_TIME_Relative retransmit_timeout;

  /**
   * Time when the Acknowledgement was queued
   */
  struct GNUNET_TIME_Absolute ack_time_registered;

  /**
   * Queued Acknowledgement deadline
   */
  struct GNUNET_TIME_Relative ack_time_deadline;

  /**
   * Mesh transmit timeout
   */
  struct GNUNET_TIME_Relative mesh_retry_timeout;

  /**
   * Data retransmission timeout
   */
  struct GNUNET_TIME_Relative data_retransmit_timeout;

  /**
   * The state of the protocol associated with this socket
   */
  enum State state;

  /**
   * Whether testing mode is active or not
   */
  int testing_active;

  /**
   * Is receive closed
   */
  int receive_closed;

  /**
   * Is transmission closed
   */
  int transmit_closed;

  /**
   * The application port number (type: uint32_t)
   */
  GNUNET_MESH_ApplicationType port;

  /**
   * The write sequence number to be set incase of testing
   */
  uint32_t testing_set_write_sequence_number_value;

  /**
   * Write sequence number. Set to random when sending HELLO(client) and
   * HELLO_ACK(server) 
   */
  uint32_t write_sequence_number;

  /**
   * Read sequence number. This number's value is determined during handshake
   */
  uint32_t read_sequence_number;

  /**
   * The receiver buffer size
   */
  uint32_t receive_buffer_size;

  /**
   * The receiver buffer boundaries
   */
  uint32_t receive_buffer_boundaries[GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH];

  /**
   * receiver's available buffer after the last acknowledged packet
   */
  uint32_t receiver_window_available;

  /**
   * The offset pointer used during write operation
   */
  uint32_t write_offset;

  /**
   * The offset after which we are expecting data
   */
  uint32_t read_offset;

  /**
   * The offset upto which user has read from the received buffer
   */
  uint32_t copy_offset;

  /**
   * The maximum size of the data message payload this stream handle can send
   */
  uint16_t max_payload_size;
};


/**
 * A socket for listening
 */
struct GNUNET_STREAM_ListenSocket
{
  /**
   * The mesh handle
   */
  struct GNUNET_MESH_Handle *mesh;

  /**
   * Handle to statistics
   */
  struct GNUNET_STATISTICS_Handle *stat_handle;

  /**
   * Our configuration
   */
  struct GNUNET_CONFIGURATION_Handle *cfg;

  /**
   * Handle to the lock manager service
   */
  struct GNUNET_LOCKMANAGER_Handle *lockmanager;

  /**
   * The active LockingRequest from lockmanager
   */
  struct GNUNET_LOCKMANAGER_LockingRequest *locking_request;

  /**
   * Callback to call after acquring a lock and listening
   */
  GNUNET_STREAM_ListenSuccessCallback listen_ok_cb;

  /**
   * The callback function which is called after successful opening socket
   */
  GNUNET_STREAM_ListenCallback listen_cb;

  /**
   * The call back closure
   */
  void *listen_cb_cls;

  /**
   * The service port
   */
  GNUNET_MESH_ApplicationType port;
  
  /**
   * The id of the lockmanager timeout task
   */
  GNUNET_SCHEDULER_TaskIdentifier lockmanager_acquire_timeout_task;

  /**
   * The retransmit timeout
   */
  struct GNUNET_TIME_Relative retransmit_timeout;
  
  /**
   * Listen enabled?
   */
  int listening;

  /**
   * Whether testing mode is active or not
   */
  int testing_active;

  /**
   * The write sequence number to be set incase of testing
   */
  uint32_t testing_set_write_sequence_number_value;

  /**
   * The maximum size of the data message payload this stream handle can send
   */
  uint16_t max_payload_size;

};


/**
 * The IO Write Handle
 */
struct GNUNET_STREAM_WriteHandle
{
  /**
   * The socket to which this write handle is associated
   */
  struct GNUNET_STREAM_Socket *socket;

  /**
   * The write continuation callback
   */
  GNUNET_STREAM_CompletionContinuation write_cont;

  /**
   * Write continuation closure
   */
  void *write_cont_cls;

  /**
   * The packet_buffers associated with this Handle
   */
  struct GNUNET_STREAM_DataMessage *messages[GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH];

  /**
   * The bitmap of this IOHandle; Corresponding bit for a message is set when
   * it has been acknowledged by the receiver
   */
  GNUNET_STREAM_AckBitmap ack_bitmap;

  /**
   * Number of bytes in this write handle
   */
  size_t size;

  /**
   * Number of packets already transmitted from this IO handle. Retransmitted
   * packets are not taken into account here. This is used to determine which
   * packets account for retransmission and which packets occupy buffer space at
   * the receiver.
   */
  unsigned int packets_sent;

  /**
   * The maximum of the base numbers of the received acks
   */
  uint32_t max_ack_base_num;

};


/**
 * The IO Read Handle
 */
struct GNUNET_STREAM_ReadHandle
{
  /**
   * The socket to which this read handle is associated
   */
  struct GNUNET_STREAM_Socket *socket;
  
  /**
   * Callback for the read processor
   */
  GNUNET_STREAM_DataProcessor proc;

  /**
   * The closure pointer for the read processor callback
   */
  void *proc_cls;

  /**
   * Task identifier for the read io timeout task
   */
  GNUNET_SCHEDULER_TaskIdentifier read_io_timeout_task_id;

  /**
   * Task scheduled to continue a read operation.
   */
  GNUNET_SCHEDULER_TaskIdentifier read_task_id;

  /**
   * Task scheduled from GNUNET_STREAM_read() to lookup the ACK bitmap and call
   * the read processor task
   */
  GNUNET_SCHEDULER_TaskIdentifier probe_data_availability_task_id;
};


/**
 * Handle for Shutdown
 */
struct GNUNET_STREAM_ShutdownHandle
{
  /**
   * The socket associated with this shutdown handle
   */
  struct GNUNET_STREAM_Socket *socket;

  /**
   * Shutdown completion callback
   */
  GNUNET_STREAM_ShutdownCompletion completion_cb;

  /**
   * Closure for completion callback
   */
  void *completion_cls;

  /**
   * Close message retransmission task id
   */
  GNUNET_SCHEDULER_TaskIdentifier close_msg_retransmission_task_id;

  /**
   * Task scheduled to call the shutdown continuation callback
   */
  GNUNET_SCHEDULER_TaskIdentifier call_cont_task_id;

  /**
   * Which operation to shutdown? SHUT_RD, SHUT_WR or SHUT_RDWR
   */
  int operation;  
};


/**
 * Collection of the state necessary to read and write gnunet messages 
 * to a stream socket. Should be used as closure for stream_data_processor.
 */
struct MQStreamState
{
  /**
   * Message stream tokenizer for the data received from the
   * stream socket.
   */
  struct GNUNET_SERVER_MessageStreamTokenizer *mst;

  /**
   * The stream socket to use for receiving and transmitting
   * messages with the message queue.
   */
  struct GNUNET_STREAM_Socket *socket;

  /**
   * Current read handle, NULL if no read active.
   */
  struct GNUNET_STREAM_ReadHandle *rh;

  /**
   * Current write handle, NULL if no write active.
   */
  struct GNUNET_STREAM_WriteHandle *wh;
};



/**
 * Default value in seconds for various timeouts
 */
static const unsigned int default_timeout = 10;

/**
 * The domain name for locks we use here
 */
static const char *locking_domain = "GNUNET_STREAM_APPLOCK";

/**
 * Callback function for sending queued message
 *
 * @param cls closure the socket
 * @param size number of bytes available in buf
 * @param buf where the callee should write the message
 * @return number of bytes written to buf
 */
static size_t
send_message_notify (void *cls, size_t size, void *buf)
{
  struct GNUNET_STREAM_Socket *socket = cls;
  struct MessageQueue *head;
  size_t ret;

  socket->transmit_handle = NULL; /* Remove the transmit handle */
  head = socket->queue_head;
  if (NULL == head)
    return 0; /* just to be safe */
  if (0 == size)                /* request timed out */
  {
    socket->mesh_retry_timeout = GNUNET_TIME_STD_BACKOFF
        (socket->mesh_retry_timeout);    
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Message sending to MESH timed out. Retrying in %s \n",
         GNUNET_i2s (&socket->other_peer),
         GNUNET_STRINGS_relative_time_to_string (socket->mesh_retry_timeout,
                                                 GNUNET_YES));
    socket->transmit_handle = 
        GNUNET_MESH_notify_transmit_ready (socket->tunnel,
                                           GNUNET_NO, /* Corking */
                                           socket->mesh_retry_timeout,
                                           &socket->other_peer,
                                           ntohs (head->message->size),
                                           &send_message_notify,
                                           socket);
    return 0;
  }
  ret = ntohs (head->message->size);
  GNUNET_assert (size >= ret);
  memcpy (buf, head->message, ret);
  if (NULL != head->finish_cb)
  {
    head->finish_cb (head->finish_cb_cls, socket);
  }
  GNUNET_CONTAINER_DLL_remove (socket->queue_head,
			       socket->queue_tail,
			       head);
  GNUNET_free (head->message);
  GNUNET_free (head);
  if (NULL != socket->transmit_handle)
    return ret; /* 'finish_cb' might have triggered message already! */
  head = socket->queue_head;
  if (NULL != head)    /* more pending messages to send */
  {
    socket->mesh_retry_timeout = GNUNET_TIME_UNIT_ZERO;
    socket->transmit_handle = 
        GNUNET_MESH_notify_transmit_ready (socket->tunnel,
                                           GNUNET_NO, /* Corking */
                                           socket->mesh_retry_timeout,
                                           &socket->other_peer,
                                           ntohs (head->message->size),
                                           &send_message_notify,
                                           socket);
  }
  return ret;
}


/**
 * Queues a message for sending using the mesh connection of a socket
 *
 * @param socket the socket whose mesh connection is used
 * @param message the message to be sent
 * @param finish_cb the callback to be called when the message is sent
 * @param finish_cb_cls the closure for the callback
 * @param urgent set to GNUNET_YES to add the message to the beginning of the
 *          queue; GNUNET_NO to add at the tail
 */
static void
queue_message (struct GNUNET_STREAM_Socket *socket,
               struct GNUNET_MessageHeader *message,
               SendFinishCallback finish_cb,
               void *finish_cb_cls,
               int urgent)
{
  struct MessageQueue *queue_entity;

  GNUNET_assert ((ntohs (message->type) >= GNUNET_MESSAGE_TYPE_STREAM_DATA)
                 && (ntohs (message->type)
                     <= GNUNET_MESSAGE_TYPE_STREAM_CLOSE_ACK));
  LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Queueing message of type %d and size %d\n",
       GNUNET_i2s (&socket->other_peer),
       ntohs (message->type),ntohs (message->size));
  GNUNET_assert (NULL != message);
  queue_entity = GNUNET_malloc (sizeof (struct MessageQueue));
  queue_entity->message = message;
  queue_entity->finish_cb = finish_cb;
  queue_entity->finish_cb_cls = finish_cb_cls;
  if (GNUNET_YES == urgent)
  {
    GNUNET_CONTAINER_DLL_insert (socket->queue_head, socket->queue_tail,
                                 queue_entity);
    if (NULL != socket->transmit_handle)
    {
      GNUNET_MESH_notify_transmit_ready_cancel (socket->transmit_handle);
      socket->transmit_handle = NULL;
    }
  }
  else
    GNUNET_CONTAINER_DLL_insert_tail (socket->queue_head,
                                      socket->queue_tail,
                                      queue_entity);
  if (NULL == socket->transmit_handle)
  {
    socket->mesh_retry_timeout = GNUNET_TIME_UNIT_ZERO;
    socket->transmit_handle = 
	GNUNET_MESH_notify_transmit_ready (socket->tunnel,
					   GNUNET_NO, /* Corking */
                                           socket->mesh_retry_timeout,
					   &socket->other_peer,
					   ntohs (message->size),
					   &send_message_notify,
					   socket);
  }
}


/**
 * Copies a message and queues it for sending using the mesh connection of
 * given socket 
 *
 * @param socket the socket whose mesh connection is used
 * @param message the message to be sent
 * @param finish_cb the callback to be called when the message is sent
 * @param finish_cb_cls the closure for the callback
 */
static void
copy_and_queue_message (struct GNUNET_STREAM_Socket *socket,
                        const struct GNUNET_MessageHeader *message,
                        SendFinishCallback finish_cb,
                        void *finish_cb_cls)
{
  struct GNUNET_MessageHeader *msg_copy;
  uint16_t size;
  
  size = ntohs (message->size);
  msg_copy = GNUNET_malloc (size);
  memcpy (msg_copy, message, size);
  queue_message (socket, msg_copy, finish_cb, finish_cb_cls, GNUNET_NO);
}


/**
 * Writes data using the given socket. The amount of data written is limited by
 * the receiver_window_size
 *
 * @param socket the socket to use
 */
static void 
write_data (struct GNUNET_STREAM_Socket *socket);


/**
 * Task for retransmitting data messages if they aren't ACK before their ack
 * deadline 
 *
 * @param cls the socket
 * @param tc the Task context
 */
static void
data_retransmission_task (void *cls,
                          const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_STREAM_Socket *socket = cls;
  
  socket->data_retransmission_task_id = GNUNET_SCHEDULER_NO_TASK;
  if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
    return;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s: Retransmitting DATA...\n", GNUNET_i2s (&socket->other_peer));
  write_data (socket);
}


/**
 * Task for sending ACK message
 *
 * @param cls the socket
 * @param tc the Task context
 */
static void
ack_task (void *cls,
          const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_STREAM_Socket *socket = cls;
  struct GNUNET_STREAM_AckMessage *ack_msg;

  socket->ack_task_id = GNUNET_SCHEDULER_NO_TASK;
  if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
    return;
  /* Create the ACK Message */
  ack_msg = GNUNET_malloc (sizeof (struct GNUNET_STREAM_AckMessage));
  ack_msg->header.size = htons (sizeof (struct 
                                               GNUNET_STREAM_AckMessage));
  ack_msg->header.type = htons (GNUNET_MESSAGE_TYPE_STREAM_ACK);
  ack_msg->bitmap = GNUNET_htonll (socket->ack_bitmap);
  ack_msg->base_sequence_number = htonl (socket->read_sequence_number);
  ack_msg->receive_window_remaining = 
    htonl (RECEIVE_BUFFER_SIZE - socket->receive_buffer_size);
  /* Queue up ACK for immediate sending */
  queue_message (socket, &ack_msg->header, NULL, NULL, GNUNET_YES);
}


/**
 * Retransmission task for shutdown messages
 *
 * @param cls the shutdown handle
 * @param tc the Task Context
 */
static void
close_msg_retransmission_task (void *cls,
                               const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_STREAM_ShutdownHandle *shutdown_handle = cls;
  struct GNUNET_MessageHeader *msg;
  struct GNUNET_STREAM_Socket *socket;

  shutdown_handle->close_msg_retransmission_task_id = GNUNET_SCHEDULER_NO_TASK;
  GNUNET_assert (NULL != shutdown_handle);
  if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
    return;
  socket = shutdown_handle->socket;
  msg = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader));
  msg->size = htons (sizeof (struct GNUNET_MessageHeader));
  switch (shutdown_handle->operation)
  {
  case SHUT_RDWR:
    msg->type = htons (GNUNET_MESSAGE_TYPE_STREAM_CLOSE);
    break;
  case SHUT_RD:
    msg->type = htons (GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE);
    break;
  case SHUT_WR:
    msg->type = htons (GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE);
    break;
  default:
    GNUNET_free (msg);
    shutdown_handle->close_msg_retransmission_task_id = 
      GNUNET_SCHEDULER_NO_TASK;
    return;
  }
  queue_message (socket, msg, NULL, NULL, GNUNET_NO);
  shutdown_handle->close_msg_retransmission_task_id =
    GNUNET_SCHEDULER_add_delayed (socket->retransmit_timeout,
                                  &close_msg_retransmission_task,
                                  shutdown_handle);
}


/**
 * Function to modify a bit in GNUNET_STREAM_AckBitmap
 *
 * @param bitmap the bitmap to modify
 * @param bit the bit number to modify
 * @param value GNUNET_YES to on, GNUNET_NO to off
 */
static void
ackbitmap_modify_bit (GNUNET_STREAM_AckBitmap *bitmap,
		      unsigned int bit, 
		      int value)
{
  GNUNET_assert (bit < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH);
  if (GNUNET_YES == value)
    *bitmap |= (1LL << bit);
  else
    *bitmap &= ~(1LL << bit);
}


/**
 * Function to check if a bit is set in the GNUNET_STREAM_AckBitmap
 *
 * @param bitmap address of the bitmap that has to be checked
 * @param bit the bit number to check
 * @return GNUNET_YES if the bit is set; GNUNET_NO if not
 */
static uint8_t
ackbitmap_is_bit_set (const GNUNET_STREAM_AckBitmap *bitmap,
                      unsigned int bit)
{
  GNUNET_assert (bit < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH);
  return 0 != (*bitmap & (1LL << bit));
}


/**
 * Writes data using the given socket. The amount of data written is limited by
 * the receiver_window_size
 *
 * @param socket the socket to use
 */
static void 
write_data (struct GNUNET_STREAM_Socket *socket)
{
  struct GNUNET_STREAM_WriteHandle *io_handle = socket->write_handle;
  unsigned int packet;
  
  for (packet=0; packet < io_handle->packets_sent; packet++)
  {
    if (GNUNET_NO == ackbitmap_is_bit_set (&io_handle->ack_bitmap,
					   packet))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
	   "%s: Retransmitting DATA message with sequence %u\n",
	   GNUNET_i2s (&socket->other_peer),
	   ntohl (io_handle->messages[packet]->sequence_number));
      copy_and_queue_message (socket,
			      &io_handle->messages[packet]->header,
			      NULL,
			      NULL);
    }
  }
  /* Now send new packets if there is enough buffer space */
  while ((packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH) &&
         (NULL != io_handle->messages[packet]) &&
         (socket->receiver_window_available 
          >= ntohs (io_handle->messages[packet]->header.size)))
  {
    socket->receiver_window_available -= 
      ntohs (io_handle->messages[packet]->header.size);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Placing DATA message with sequence %u in send queue\n",
         GNUNET_i2s (&socket->other_peer),
         ntohl (io_handle->messages[packet]->sequence_number));
    copy_and_queue_message (socket,
                            &io_handle->messages[packet]->header,
                            NULL,
                            NULL);
    packet++;
  }
  io_handle->packets_sent = packet;
  if (GNUNET_SCHEDULER_NO_TASK == socket->data_retransmission_task_id)
  {
    socket->data_retransmit_timeout = GNUNET_TIME_STD_BACKOFF
        (socket->data_retransmit_timeout);
    socket->data_retransmission_task_id = 
        GNUNET_SCHEDULER_add_delayed (socket->data_retransmit_timeout,
                                      &data_retransmission_task,
                                      socket);
  }
}


/**
 * Cleansup the sockets read handle
 *
 * @param socket the socket whose read handle has to be cleanedup
 */
static void
cleanup_read_handle (struct GNUNET_STREAM_Socket *socket)
{
  struct GNUNET_STREAM_ReadHandle *read_handle;

  read_handle = socket->read_handle;
  /* Read io time task should be there; if it is already executed then this
  read handle is not valid; However upon scheduler shutdown the read io task
  may be executed before */
  if (GNUNET_SCHEDULER_NO_TASK != read_handle->read_io_timeout_task_id)
    GNUNET_SCHEDULER_cancel (read_handle->read_io_timeout_task_id);
  /* reading task may be present; if so we have to stop it */
  if (GNUNET_SCHEDULER_NO_TASK != read_handle->read_task_id)
    GNUNET_SCHEDULER_cancel (read_handle->read_task_id);
  if (GNUNET_SCHEDULER_NO_TASK != read_handle->probe_data_availability_task_id)
    GNUNET_SCHEDULER_cancel (read_handle->probe_data_availability_task_id);
  GNUNET_free (read_handle);
  socket->read_handle = NULL;
}


/**
 * Task for calling the read processor
 *
 * @param cls the socket
 * @param tc the task context
 */
static void
call_read_processor (void *cls,
                     const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_STREAM_Socket *socket = cls;
  struct GNUNET_STREAM_ReadHandle *read_handle;
  GNUNET_STREAM_DataProcessor proc;
  void *proc_cls;
  size_t read_size;
  size_t valid_read_size;
  unsigned int packet;
  uint32_t sequence_increase;
  uint32_t offset_increase;

  read_handle = socket->read_handle;
  GNUNET_assert (NULL != read_handle);
  read_handle->read_task_id = GNUNET_SCHEDULER_NO_TASK;
  if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
    return;
  if (NULL == socket->receive_buffer) 
    return;
  GNUNET_assert (NULL != read_handle->proc);
  /* Check the bitmap for any holes */
  for (packet=0; packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH; packet++)
  {
    if (GNUNET_NO == ackbitmap_is_bit_set (&socket->ack_bitmap,
                                           packet))
      break;
  }
  /* We only call read processor if we have the first packet */
  GNUNET_assert (0 < packet);
  valid_read_size = 
    socket->receive_buffer_boundaries[packet-1] - socket->copy_offset;
  GNUNET_assert (0 != valid_read_size);
  proc = read_handle->proc;
  proc_cls = read_handle->proc_cls;
  cleanup_read_handle (socket);
  /* Call the data processor */
  LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Calling read processor\n",
       GNUNET_i2s (&socket->other_peer));
  read_size = proc (proc_cls, GNUNET_STREAM_OK,
                    socket->receive_buffer + socket->copy_offset,
                    valid_read_size);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Read processor read %d bytes\n",
       GNUNET_i2s (&socket->other_peer), read_size);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Read processor completed successfully\n",
       GNUNET_i2s (&socket->other_peer));
  GNUNET_assert (read_size <= valid_read_size);
  socket->copy_offset += read_size;
  /* Determine upto which packet we can remove from the buffer */
  for (packet = 0; packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH; packet++)
  {
    if (socket->copy_offset == socket->receive_buffer_boundaries[packet])
    { 
      packet++; 
      break;
    }
    if (socket->copy_offset < socket->receive_buffer_boundaries[packet])
      break;
  }
  /* If no packets can be removed we can't move the buffer */
  if (0 == packet) 
    return;
  sequence_increase = packet;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s: Sequence increase after read processor completion: %u\n",
       GNUNET_i2s (&socket->other_peer), sequence_increase);
  /* Shift the data in the receive buffer */
  socket->receive_buffer = 
    memmove (socket->receive_buffer,
	     socket->receive_buffer 
	     + socket->receive_buffer_boundaries[sequence_increase-1],
	     socket->receive_buffer_size
	     - socket->receive_buffer_boundaries[sequence_increase-1]);
  /* Shift the bitmap */
  socket->ack_bitmap = socket->ack_bitmap >> sequence_increase;
  /* Set read_sequence_number */
  socket->read_sequence_number += sequence_increase;
  /* Set read_offset */
  offset_increase = socket->receive_buffer_boundaries[sequence_increase-1];
  socket->read_offset += offset_increase;
  /* Fix copy_offset */
  GNUNET_assert (offset_increase <= socket->copy_offset);
  socket->copy_offset -= offset_increase;
  /* Fix relative boundaries */
  for (packet=0; packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH; packet++)
  {
    if (packet < (GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH - sequence_increase))
    {
      uint32_t ahead_buffer_boundary;

      ahead_buffer_boundary = 
	socket->receive_buffer_boundaries[packet + sequence_increase];
      if (0 == ahead_buffer_boundary)
	socket->receive_buffer_boundaries[packet] = 0;
      else
      {
	GNUNET_assert (offset_increase < ahead_buffer_boundary);
	socket->receive_buffer_boundaries[packet] = 
	  ahead_buffer_boundary - offset_increase;
      }
    }
    else
      socket->receive_buffer_boundaries[packet] = 0;
  }
}


/**
 * Cancels the existing read io handle
 *
 * @param cls the closure from the SCHEDULER call
 * @param tc the task context
 */
static void
read_io_timeout (void *cls,
                 const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_STREAM_Socket *socket = cls;
  struct GNUNET_STREAM_ReadHandle *read_handle;
  GNUNET_STREAM_DataProcessor proc;
  void *proc_cls;

  read_handle = socket->read_handle;
  GNUNET_assert (NULL != read_handle);
  read_handle->read_io_timeout_task_id = GNUNET_SCHEDULER_NO_TASK;
  if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
    return;
  if (read_handle->read_task_id != GNUNET_SCHEDULER_NO_TASK)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Read task timedout - Cancelling it\n",
         GNUNET_i2s (&socket->other_peer));
    GNUNET_SCHEDULER_cancel (read_handle->read_task_id);
    read_handle->read_task_id = GNUNET_SCHEDULER_NO_TASK;
  }
  proc = read_handle->proc;
  proc_cls = read_handle->proc_cls;
  GNUNET_free (read_handle);
  socket->read_handle = NULL;
  /* Call the read processor to signal timeout */
  proc (proc_cls,
        GNUNET_STREAM_TIMEOUT,
        NULL,
        0);
}


/**
 * Handler for DATA messages; Same for both client and server
 *
 * @param socket the socket through which the ack was received
 * @param tunnel connection to the other end
 * @param sender who sent the message
 * @param msg the data message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
handle_data (struct GNUNET_STREAM_Socket *socket,
             struct GNUNET_MESH_Tunnel *tunnel,
             const struct GNUNET_PeerIdentity *sender,
             const struct GNUNET_STREAM_DataMessage *msg,
             const struct GNUNET_ATS_Information*atsi)
{
  const void *payload;
  struct GNUNET_TIME_Relative ack_deadline_rel;
  uint32_t bytes_needed;
  uint32_t relative_offset;
  uint32_t relative_sequence_number;
  uint16_t size;

  size = htons (msg->header.size);
  if (size < sizeof (struct GNUNET_STREAM_DataMessage))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (0 != memcmp (sender, &socket->other_peer,
		   sizeof (struct GNUNET_PeerIdentity)))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "%s: Received DATA from non-confirming peer\n",
	 GNUNET_i2s (&socket->other_peer));
    return GNUNET_YES;
  }
  switch (socket->state)
  {
  case STATE_ESTABLISHED:
  case STATE_TRANSMIT_CLOSED:
  case STATE_TRANSMIT_CLOSE_WAIT:      
    /* check if the message's sequence number is in the range we are
       expecting */
    relative_sequence_number = 
      ntohl (msg->sequence_number) - socket->read_sequence_number;
    if ( relative_sequence_number >= GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "%s: Ignoring received message with sequence number %u\n",
           GNUNET_i2s (&socket->other_peer),
           ntohl (msg->sequence_number));
      /* Start ACK sending task if one is not already present */
      if (GNUNET_SCHEDULER_NO_TASK == socket->ack_task_id)
      {
        socket->ack_task_id = 
          GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_ntoh
                                        (msg->ack_deadline),
                                        &ack_task,
                                        socket);
      }
      return GNUNET_YES;
    }      
    /* Check if we have already seen this message */
    if (GNUNET_YES == ackbitmap_is_bit_set (&socket->ack_bitmap,
                                            relative_sequence_number))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "%s: Ignoring already received message with sequence number %u\n",
           GNUNET_i2s (&socket->other_peer),
           ntohl (msg->sequence_number));
      /* Start ACK sending task if one is not already present */
      if (GNUNET_SCHEDULER_NO_TASK == socket->ack_task_id)
      {
        socket->ack_task_id = 
          GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_ntoh
                                        (msg->ack_deadline), &ack_task, socket);
      }
      return GNUNET_YES;
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%1$s: Receiving DATA with sequence number: %2$u and size: %3$d from "
         "%1$s\n", GNUNET_i2s (&socket->other_peer),
         ntohl (msg->sequence_number), ntohs (msg->header.size));
    /* Check if we have to allocate the buffer */
    size -= sizeof (struct GNUNET_STREAM_DataMessage);
    relative_offset = ntohl (msg->offset) - socket->read_offset;
    bytes_needed = relative_offset + size;
    if (bytes_needed > socket->receive_buffer_size)
    {
      if (bytes_needed <= RECEIVE_BUFFER_SIZE)
      {
        socket->receive_buffer = GNUNET_realloc (socket->receive_buffer,
                                                 bytes_needed);
        socket->receive_buffer_size = bytes_needed;
      }
      else
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG,
             "%s: Cannot accommodate packet %d as buffer is full\n",
             GNUNET_i2s (&socket->other_peer), ntohl (msg->sequence_number));
        return GNUNET_YES;
      }
    }
    /* Copy Data to buffer */
    payload = &msg[1];
    GNUNET_assert (relative_offset + size <= socket->receive_buffer_size);
    memcpy (socket->receive_buffer + relative_offset, payload, size);
    socket->receive_buffer_boundaries[relative_sequence_number] = 
	relative_offset + size;
    /* Modify the ACK bitmap */
    ackbitmap_modify_bit (&socket->ack_bitmap, relative_sequence_number,
			  GNUNET_YES);
    /* Start ACK sending task if one is not already present */
    ack_deadline_rel = GNUNET_TIME_relative_ntoh (msg->ack_deadline);
    if (GNUNET_SCHEDULER_NO_TASK == socket->ack_task_id)
    {
      ack_deadline_rel = 
	  GNUNET_TIME_relative_min (ack_deadline_rel,
				    GNUNET_TIME_relative_multiply
				    (GNUNET_TIME_UNIT_SECONDS, 300));
      socket->ack_task_id = 
	  GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_ntoh 
					(msg->ack_deadline), &ack_task, socket);
      socket->ack_time_registered = GNUNET_TIME_absolute_get ();
      socket->ack_time_deadline = ack_deadline_rel;
    }
    else
    {
      struct GNUNET_TIME_Relative ack_time_past;
      struct GNUNET_TIME_Relative ack_time_remaining;
      struct GNUNET_TIME_Relative ack_time_min;
      ack_time_past = 
	  GNUNET_TIME_absolute_get_duration (socket->ack_time_registered);
      ack_time_remaining = GNUNET_TIME_relative_subtract
	  (socket->ack_time_deadline, ack_time_past);
      ack_time_min = GNUNET_TIME_relative_min (ack_time_remaining,
					       ack_deadline_rel);
      if (0 == memcmp(&ack_deadline_rel, &ack_time_min,
		      sizeof (struct GNUNET_TIME_Relative)))
      {
	ack_deadline_rel = ack_time_min;
	GNUNET_SCHEDULER_cancel (socket->ack_task_id);
	socket->ack_task_id = GNUNET_SCHEDULER_add_delayed (ack_deadline_rel,
							    &ack_task, socket);
	socket->ack_time_registered = GNUNET_TIME_absolute_get ();
	socket->ack_time_deadline = ack_deadline_rel;
      }
    }
    if ((NULL != socket->read_handle) /* A read handle is waiting */
        /* There is no current read task */
        && (GNUNET_SCHEDULER_NO_TASK == socket->read_handle->read_task_id)
        /* We have the first packet */
        && (GNUNET_YES == ackbitmap_is_bit_set(&socket->ack_bitmap, 0)))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Scheduling read processor\n",
	   GNUNET_i2s (&socket->other_peer));
      socket->read_handle->read_task_id =
	  GNUNET_SCHEDULER_add_now (&call_read_processor, socket);
    }
    break;
  default:
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Received data message when it cannot be handled\n",
         GNUNET_i2s (&socket->other_peer));
    break;
  }
  return GNUNET_YES;
}


/**
 * Client's message Handler for GNUNET_MESSAGE_TYPE_STREAM_DATA
 *
 * @param cls the socket (set from GNUNET_MESH_connect)
 * @param tunnel connection to the other end
 * @param tunnel_ctx place to store local state associated with the tunnel
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
client_handle_data (void *cls,
                    struct GNUNET_MESH_Tunnel *tunnel,
                    void **tunnel_ctx,
                    const struct GNUNET_PeerIdentity *sender,
                    const struct GNUNET_MessageHeader *message,
                    const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = cls;

  return handle_data (socket, tunnel, sender, 
                      (const struct GNUNET_STREAM_DataMessage *) message, atsi);
}


/**
 * Callback to set state to ESTABLISHED
 *
 * @param cls the closure NULL;
 * @param socket the socket to requiring state change
 */
static void
set_state_established (void *cls,
                       struct GNUNET_STREAM_Socket *socket)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG, 
       "%s: Attaining ESTABLISHED state\n",
       GNUNET_i2s (&socket->other_peer));
  socket->write_offset = 0;
  socket->read_offset = 0;
  socket->state = STATE_ESTABLISHED;
  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK !=
                 socket->control_retransmission_task_id);
  GNUNET_SCHEDULER_cancel (socket->control_retransmission_task_id);
  socket->control_retransmission_task_id = GNUNET_SCHEDULER_NO_TASK;
  if (NULL != socket->lsocket)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Calling listen callback\n",
         GNUNET_i2s (&socket->other_peer));
    if (GNUNET_SYSERR == 
        socket->lsocket->listen_cb (socket->lsocket->listen_cb_cls,
                                    socket,
                                    &socket->other_peer))
    {
      socket->state = STATE_CLOSED;
      /* FIXME: We should close in a decent way (send RST) */
      GNUNET_MESH_tunnel_destroy (socket->tunnel); /* Destroy the tunnel */
      GNUNET_free (socket);
    }
  }
  else
    socket->open_cb (socket->open_cls, socket);
}


/**
 * Callback to set state to HELLO_WAIT
 *
 * @param cls the closure from queue_message
 * @param socket the socket to requiring state change
 */
static void
set_state_hello_wait (void *cls,
                      struct GNUNET_STREAM_Socket *socket)
{
  GNUNET_assert (STATE_INIT == socket->state);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s: Attaining HELLO_WAIT state\n",
       GNUNET_i2s (&socket->other_peer));
  socket->state = STATE_HELLO_WAIT;
}


/**
 * Callback to set state to CLOSE_WAIT
 *
 * @param cls the closure from queue_message
 * @param socket the socket requiring state change
 */
static void
set_state_close_wait (void *cls,
                      struct GNUNET_STREAM_Socket *socket)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s: Attaing CLOSE_WAIT state\n",
       GNUNET_i2s (&socket->other_peer));
  socket->state = STATE_CLOSE_WAIT;
  GNUNET_free_non_null (socket->receive_buffer); /* Free the receive buffer */
  socket->receive_buffer = NULL;
  socket->receive_buffer_size = 0;
}


/**
 * Callback to set state to RECEIVE_CLOSE_WAIT
 *
 * @param cls the closure from queue_message
 * @param socket the socket requiring state change
 */
static void
set_state_receive_close_wait (void *cls,
                              struct GNUNET_STREAM_Socket *socket)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s: Attaing RECEIVE_CLOSE_WAIT state\n",
       GNUNET_i2s (&socket->other_peer));
  socket->state = STATE_RECEIVE_CLOSE_WAIT;
  GNUNET_free_non_null (socket->receive_buffer); /* Free the receive buffer */
  socket->receive_buffer = NULL;
  socket->receive_buffer_size = 0;
}


/**
 * Callback to set state to TRANSMIT_CLOSE_WAIT
 *
 * @param cls the closure from queue_message
 * @param socket the socket requiring state change
 */
static void
set_state_transmit_close_wait (void *cls,
                               struct GNUNET_STREAM_Socket *socket)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s: Attaing TRANSMIT_CLOSE_WAIT state\n",
       GNUNET_i2s (&socket->other_peer));
  socket->state = STATE_TRANSMIT_CLOSE_WAIT;
}


/**
 * Callback to set state to CLOSED
 *
 * @param cls the closure from queue_message
 * @param socket the socket requiring state change
 */
static void
set_state_closed (void *cls,
                  struct GNUNET_STREAM_Socket *socket)
{
  socket->state = STATE_CLOSED;
}


/**
 * Returns GNUNET_MESSAGE_TYPE_STREAM_HELLO
 *
 * @return the generate hello message
 */
static struct GNUNET_MessageHeader *
generate_hello (struct GNUNET_STREAM_Socket *socket)
{
  struct GNUNET_STREAM_HelloMessage *msg;

  msg = GNUNET_malloc (sizeof (struct GNUNET_STREAM_HelloMessage));
  msg->header.type = htons (GNUNET_MESSAGE_TYPE_STREAM_HELLO);
  msg->header.size = htons (sizeof (struct GNUNET_STREAM_HelloMessage));
  msg->port = GNUNET_htonll ((uint64_t) socket->port);
  return &msg->header;
}


/**
 * Returns a new HelloAckMessage. Also sets the write sequence number for the
 * socket
 *
 * @param socket the socket for which this HelloAckMessage has to be generated
 * @param generate_seq GNUNET_YES to generate the write sequence number,
 *          GNUNET_NO to use the existing sequence number
 * @return the HelloAckMessage
 */
static struct GNUNET_STREAM_HelloAckMessage *
generate_hello_ack (struct GNUNET_STREAM_Socket *socket,
                    int generate_seq)
{
  struct GNUNET_STREAM_HelloAckMessage *msg;

  if (GNUNET_YES == generate_seq)
  {
    if (GNUNET_YES == socket->testing_active)
      socket->write_sequence_number =
        socket->testing_set_write_sequence_number_value;
    else
      socket->write_sequence_number = 
        GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
    LOG_DEBUG ("%s: write sequence number %u\n",
               GNUNET_i2s (&socket->other_peer),
               (unsigned int) socket->write_sequence_number);
  }
  msg = GNUNET_malloc (sizeof (struct GNUNET_STREAM_HelloAckMessage));
  msg->header.size = 
    htons (sizeof (struct GNUNET_STREAM_HelloAckMessage));
  msg->header.type = htons (GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK);
  msg->sequence_number = htonl (socket->write_sequence_number);
  msg->receiver_window_size = htonl (RECEIVE_BUFFER_SIZE);
  return msg;
}


/**
 * Task for retransmitting control messages if they aren't ACK'ed before a
 * deadline
 *
 * @param cls the socket
 * @param tc the Task context
 */
static void
control_retransmission_task (void *cls,
                             const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_STREAM_Socket *socket = cls;
    
  socket->control_retransmission_task_id = GNUNET_SCHEDULER_NO_TASK;
  if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
    return;
  LOG_DEBUG ("%s: Retransmitting a control message\n",
                 GNUNET_i2s (&socket->other_peer));
  switch (socket->state)
  {
  case STATE_INIT:    
    GNUNET_break (0);
    break;
  case STATE_LISTEN:
    GNUNET_break (0);
    break;
  case STATE_HELLO_WAIT:
    if (NULL == socket->lsocket) /* We are client */
      queue_message (socket, generate_hello (socket), NULL, NULL, GNUNET_NO);
    else
      queue_message (socket,
                     (struct GNUNET_MessageHeader *)
                     generate_hello_ack (socket, GNUNET_NO), NULL, NULL,
                     GNUNET_NO);
    socket->control_retransmission_task_id =
    GNUNET_SCHEDULER_add_delayed (socket->retransmit_timeout,
                                  &control_retransmission_task, socket);
    break;
  case STATE_ESTABLISHED:
    if (NULL == socket->lsocket)
      queue_message (socket,
                     (struct GNUNET_MessageHeader *)
                     generate_hello_ack (socket, GNUNET_NO), NULL, NULL,
                     GNUNET_NO);
    else
      GNUNET_break (0);
    break;
  default:
    GNUNET_break (0);
  }  
}


/**
 * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK
 *
 * @param cls the socket (set from GNUNET_MESH_connect)
 * @param tunnel connection to the other end
 * @param tunnel_ctx this is NULL
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
client_handle_hello_ack (void *cls,
                         struct GNUNET_MESH_Tunnel *tunnel,
                         void **tunnel_ctx,
                         const struct GNUNET_PeerIdentity *sender,
                         const struct GNUNET_MessageHeader *message,
                         const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = cls;
  const struct GNUNET_STREAM_HelloAckMessage *ack_msg;
  struct GNUNET_STREAM_HelloAckMessage *reply;

  if (0 != memcmp (sender, &socket->other_peer,
		   sizeof (struct GNUNET_PeerIdentity)))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Received HELLO_ACK from non-confirming peer\n",
         GNUNET_i2s (&socket->other_peer));
    return GNUNET_YES;
  }
  ack_msg = (const struct GNUNET_STREAM_HelloAckMessage *) message;
  LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Received HELLO_ACK from %s\n",
       GNUNET_i2s (&socket->other_peer), GNUNET_i2s (&socket->other_peer));
  GNUNET_assert (socket->tunnel == tunnel);
  switch (socket->state)
  {
  case STATE_HELLO_WAIT:
    socket->read_sequence_number = ntohl (ack_msg->sequence_number);
    LOG_DEBUG ("%s: Read sequence number %u\n", 
               GNUNET_i2s (&socket->other_peer), socket->read_sequence_number);
    socket->receiver_window_available = ntohl (ack_msg->receiver_window_size);
    reply = generate_hello_ack (socket, GNUNET_YES);
    queue_message (socket, &reply->header, &set_state_established,
                   NULL, GNUNET_NO);    
    return GNUNET_OK;
  case STATE_ESTABLISHED:
    // call statistics (# ACKs ignored++)
    GNUNET_assert (GNUNET_SCHEDULER_NO_TASK ==
                   socket->control_retransmission_task_id);
    socket->control_retransmission_task_id =
      GNUNET_SCHEDULER_add_now (&control_retransmission_task, socket);
    return GNUNET_OK;
  default:
    LOG_DEBUG ("%1$s: Server %1$s sent HELLO_ACK when in state %2$d\n", 
	       GNUNET_i2s (&socket->other_peer), socket->state);
    socket->state = STATE_CLOSED; // introduce STATE_ERROR?
    return GNUNET_SYSERR;
  }
}


/**
 * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_RESET
 *
 * @param cls the socket (set from GNUNET_MESH_connect)
 * @param tunnel connection to the other end
 * @param tunnel_ctx this is NULL
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
client_handle_reset (void *cls,
                     struct GNUNET_MESH_Tunnel *tunnel,
                     void **tunnel_ctx,
                     const struct GNUNET_PeerIdentity *sender,
                     const struct GNUNET_MessageHeader *message,
                     const struct GNUNET_ATS_Information*atsi)
{
  // struct GNUNET_STREAM_Socket *socket = cls;

  return GNUNET_OK;
}


/**
 * Frees the socket's receive buffers, marks the socket as receive closed and
 * calls the DataProcessor with GNUNET_STREAM_SHUTDOWN status if a read handle
 * is present
 *
 * @param socket the socket
 */
static void
do_receive_shutdown (struct GNUNET_STREAM_Socket *socket)
{
  socket->receive_closed = GNUNET_YES;  
  GNUNET_free_non_null (socket->receive_buffer); /* Free the receive buffer */
  socket->receive_buffer = NULL;
  socket->receive_buffer_size = 0;
  if (NULL != socket->read_handle)
  {
    GNUNET_STREAM_DataProcessor proc;
    void *proc_cls;

    proc = socket->read_handle->proc;
    proc_cls = socket->read_handle->proc_cls;
    GNUNET_STREAM_read_cancel (socket->read_handle);
    socket->read_handle = NULL;
    if (NULL != proc)
      proc (proc_cls, GNUNET_STREAM_SHUTDOWN, NULL, 0);
  }
}


/**
 * Marks the socket as transmit closed and calls the CompletionContinuation with
 * GNUNET_STREAM_SHUTDOWN status if a write handle is present
 *
 * @param socket the socket
 */
static void
do_transmit_shutdown (struct GNUNET_STREAM_Socket *socket)
{
  socket->transmit_closed = GNUNET_YES;
  /* If write handle is present call it with GNUNET_STREAM_SHUTDOWN to signal
     that that stream has been shutdown */
  if (NULL != socket->write_handle)
  {
    GNUNET_STREAM_CompletionContinuation wc;
    void *wc_cls;

    wc = socket->write_handle->write_cont;
    wc_cls = socket->write_handle->write_cont_cls;
    GNUNET_STREAM_write_cancel (socket->write_handle);
    socket->write_handle = NULL;
    if (NULL != wc)
      wc (wc_cls,
	  GNUNET_STREAM_SHUTDOWN, 0);
  }
}


/**
 * Common message handler for handling TRANSMIT_CLOSE messages
 *
 * @param socket the socket through which the ack was received
 * @param tunnel connection to the other end
 * @param sender who sent the message
 * @param msg the transmit close message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
handle_transmit_close (struct GNUNET_STREAM_Socket *socket,
                       struct GNUNET_MESH_Tunnel *tunnel,
                       const struct GNUNET_PeerIdentity *sender,
                       const struct GNUNET_MessageHeader *msg,
                       const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_MessageHeader *reply;

  switch (socket->state)
  {
  case STATE_INIT:
  case STATE_LISTEN:
  case STATE_HELLO_WAIT:
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Ignoring RECEIVE_CLOSE as it cannot be handled now\n",
         GNUNET_i2s (&socket->other_peer));
    return GNUNET_OK;
  default:
    break;
  }
  /* Send TRANSMIT_CLOSE_ACK */
  reply = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader));
  reply->type = htons (GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE_ACK);
  reply->size = htons (sizeof (struct GNUNET_MessageHeader));
  queue_message (socket, reply, NULL, NULL, GNUNET_NO);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "%1$s: Received TRANSMIT_CLOSE from %1$s\n",
       GNUNET_i2s (&socket->other_peer));
  switch(socket->state)
  {
  case STATE_RECEIVE_CLOSED:
  case STATE_RECEIVE_CLOSE_WAIT:
  case STATE_CLOSE_WAIT:
  case STATE_CLOSED:
    return GNUNET_OK;
  default:
    break;
  }
  do_receive_shutdown (socket);
  if (GNUNET_YES == socket->transmit_closed)
    socket->state = STATE_CLOSED;
  else
    socket->state = STATE_RECEIVE_CLOSED;
  return GNUNET_OK;
}


/**
 * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE
 *
 * @param cls the socket (set from GNUNET_MESH_connect)
 * @param tunnel connection to the other end
 * @param tunnel_ctx this is NULL
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
client_handle_transmit_close (void *cls,
                              struct GNUNET_MESH_Tunnel *tunnel,
                              void **tunnel_ctx,
                              const struct GNUNET_PeerIdentity *sender,
                              const struct GNUNET_MessageHeader *message,
                              const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = cls;
  
  return handle_transmit_close (socket,
                                tunnel,
                                sender,
                                (struct GNUNET_MessageHeader *)message,
                                atsi);
}


/**
 * Task for calling the shutdown continuation callback
 *
 * @param cls the socket
 * @param tc the scheduler task context
 */
static void
call_cont_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_STREAM_Socket *socket = cls;
  
  GNUNET_assert (NULL != socket->shutdown_handle);
  socket->shutdown_handle->call_cont_task_id = GNUNET_SCHEDULER_NO_TASK;
  if (NULL != socket->shutdown_handle->completion_cb)
    socket->shutdown_handle->completion_cb
        (socket->shutdown_handle->completion_cls,
         socket->shutdown_handle->operation);
  GNUNET_free (socket->shutdown_handle);
  socket->shutdown_handle = NULL;
}


/**
 * Generic handler for GNUNET_MESSAGE_TYPE_STREAM_*_CLOSE_ACK messages
 *
 * @param socket the socket
 * @param tunnel connection to the other end
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @param operation the close operation which is being ACK'ed
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
handle_generic_close_ack (struct GNUNET_STREAM_Socket *socket,
                          struct GNUNET_MESH_Tunnel *tunnel,
                          const struct GNUNET_PeerIdentity *sender,
                          const struct GNUNET_MessageHeader *message,
                          const struct GNUNET_ATS_Information *atsi,
                          int operation)
{
  struct GNUNET_STREAM_ShutdownHandle *shutdown_handle;

  shutdown_handle = socket->shutdown_handle;
  if (NULL == shutdown_handle)
  {
    /* This may happen when the shudown handle is cancelled */
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Received CLOSE_ACK when shutdown handle is NULL\n",
         GNUNET_i2s (&socket->other_peer));
    return GNUNET_OK;
  }
  switch (operation)
  {
  case SHUT_RDWR:
    switch (socket->state)
    {
    case STATE_CLOSE_WAIT:
      if (SHUT_RDWR != shutdown_handle->operation)
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG,
             "%s: Received CLOSE_ACK when shutdown handle is not for "
             "SHUT_RDWR\n", GNUNET_i2s (&socket->other_peer));
        return GNUNET_OK;
      }
      LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Received CLOSE_ACK from %s\n",
           GNUNET_i2s (&socket->other_peer), GNUNET_i2s (&socket->other_peer));
      socket->state = STATE_CLOSED;
      break;
    default:
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "%s: Received CLOSE_ACK when it is not expected\n",
           GNUNET_i2s (&socket->other_peer));
      return GNUNET_OK;
    }
    break;
  case SHUT_RD:
    switch (socket->state)
    {
    case STATE_RECEIVE_CLOSE_WAIT:
      if (SHUT_RD != shutdown_handle->operation)
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG,
             "%s: Received RECEIVE_CLOSE_ACK when shutdown handle "
             "is not for SHUT_RD\n", GNUNET_i2s (&socket->other_peer));
        return GNUNET_OK;
      }
      LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Received RECEIVE_CLOSE_ACK from %s\n",
           GNUNET_i2s (&socket->other_peer), GNUNET_i2s (&socket->other_peer));
      socket->state = STATE_RECEIVE_CLOSED;
      break;
    default:
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "%s: Received RECEIVE_CLOSE_ACK when it is not expected\n",
           GNUNET_i2s (&socket->other_peer));
      return GNUNET_OK;
    }
    break;
  case SHUT_WR:
    switch (socket->state)
    {
    case STATE_TRANSMIT_CLOSE_WAIT:
      if (SHUT_WR != shutdown_handle->operation)
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG,
             "%s: Received TRANSMIT_CLOSE_ACK when shutdown handle "
             "is not for SHUT_WR\n",
             GNUNET_i2s (&socket->other_peer));
        return GNUNET_OK;
      }
      LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Received TRANSMIT_CLOSE_ACK from %s\n",
           GNUNET_i2s (&socket->other_peer), GNUNET_i2s (&socket->other_peer));
      socket->state = STATE_TRANSMIT_CLOSED;
      break;
    default:
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "%s: Received TRANSMIT_CLOSE_ACK when it is not expected\n",
           GNUNET_i2s (&socket->other_peer));          
      return GNUNET_OK;
    }
    break;
  default:
    GNUNET_assert (0);
  }
  shutdown_handle->call_cont_task_id = GNUNET_SCHEDULER_add_now
      (&call_cont_task, socket);
  if (GNUNET_SCHEDULER_NO_TASK
      != shutdown_handle->close_msg_retransmission_task_id)
  {
    GNUNET_SCHEDULER_cancel
      (shutdown_handle->close_msg_retransmission_task_id);
    shutdown_handle->close_msg_retransmission_task_id =
	GNUNET_SCHEDULER_NO_TASK;
  }
  return GNUNET_OK;
}


/**
 * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE_ACK
 *
 * @param cls the socket (set from GNUNET_MESH_connect)
 * @param tunnel connection to the other end
 * @param tunnel_ctx this is NULL
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
client_handle_transmit_close_ack (void *cls,
                                  struct GNUNET_MESH_Tunnel *tunnel,
                                  void **tunnel_ctx,
                                  const struct GNUNET_PeerIdentity *sender,
                                  const struct GNUNET_MessageHeader *message,
                                  const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = cls;

  return handle_generic_close_ack (socket,
                                   tunnel,
                                   sender,
                                   (const struct GNUNET_MessageHeader *)
                                   message,
                                   atsi,
                                   SHUT_WR);
}


/**
 * Generic handler for GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE
 *
 * @param socket the socket
 * @param tunnel connection to the other end
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
handle_receive_close (struct GNUNET_STREAM_Socket *socket,
                      struct GNUNET_MESH_Tunnel *tunnel,
                      const struct GNUNET_PeerIdentity *sender,
                      const struct GNUNET_MessageHeader *message,
                      const struct GNUNET_ATS_Information *atsi)
{
  struct GNUNET_MessageHeader *receive_close_ack;

  switch (socket->state)
  {
  case STATE_INIT:
  case STATE_LISTEN:
  case STATE_HELLO_WAIT:
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Ignoring RECEIVE_CLOSE as it cannot be handled now\n",
         GNUNET_i2s (&socket->other_peer));
    return GNUNET_OK;
  default:
    break;
  }  
  LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Received RECEIVE_CLOSE from %s\n",
       GNUNET_i2s (&socket->other_peer), GNUNET_i2s (&socket->other_peer));  
  receive_close_ack = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader));
  receive_close_ack->size = htons (sizeof (struct GNUNET_MessageHeader));
  receive_close_ack->type =
      htons (GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE_ACK);
  queue_message (socket, receive_close_ack, NULL, NULL, GNUNET_NO);
  switch (socket->state)
  {
  case STATE_TRANSMIT_CLOSED:
  case STATE_TRANSMIT_CLOSE_WAIT:
  case STATE_CLOSED:
  case STATE_CLOSE_WAIT:
    return GNUNET_OK;
  default:
    break;
  }
  do_transmit_shutdown (socket);
  if (GNUNET_YES == socket->receive_closed)
    socket->state = STATE_CLOSED;
  else
    socket->state = STATE_TRANSMIT_CLOSED;
  return GNUNET_OK;
}


/**
 * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE
 *
 * @param cls the socket (set from GNUNET_MESH_connect)
 * @param tunnel connection to the other end
 * @param tunnel_ctx this is NULL
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
client_handle_receive_close (void *cls,
                             struct GNUNET_MESH_Tunnel *tunnel,
                             void **tunnel_ctx,
                             const struct GNUNET_PeerIdentity *sender,
                             const struct GNUNET_MessageHeader *message,
                             const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = cls;

  return
    handle_receive_close (socket,
                          tunnel,
                          sender,
                          (const struct GNUNET_MessageHeader *) message,
                          atsi);
}


/**
 * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE_ACK
 *
 * @param cls the socket (set from GNUNET_MESH_connect)
 * @param tunnel connection to the other end
 * @param tunnel_ctx this is NULL
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
client_handle_receive_close_ack (void *cls,
                                 struct GNUNET_MESH_Tunnel *tunnel,
                                 void **tunnel_ctx,
                                 const struct GNUNET_PeerIdentity *sender,
                                 const struct GNUNET_MessageHeader *message,
                                 const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = cls;

  return handle_generic_close_ack (socket,
                                   tunnel,
                                   sender,
                                   (const struct GNUNET_MessageHeader *)
                                   message,
                                   atsi,
                                   SHUT_RD);
}


/**
 * Generic handler for GNUNET_MESSAGE_TYPE_STREAM_CLOSE
 *
 * @param socket the socket
 * @param tunnel connection to the other end
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
handle_close (struct GNUNET_STREAM_Socket *socket,
              struct GNUNET_MESH_Tunnel *tunnel,
              const struct GNUNET_PeerIdentity *sender,
              const struct GNUNET_MessageHeader *message,
              const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_MessageHeader *close_ack;

  switch (socket->state)
  {
  case STATE_INIT:
  case STATE_LISTEN:
  case STATE_HELLO_WAIT:
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Ignoring RECEIVE_CLOSE as it cannot be handled now\n",
         GNUNET_i2s (&socket->other_peer));
    return GNUNET_OK;
  default:
    break;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Received CLOSE from %s\n",
       GNUNET_i2s (&socket->other_peer), GNUNET_i2s (&socket->other_peer));
  close_ack = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader));
  close_ack->size = htons (sizeof (struct GNUNET_MessageHeader));
  close_ack->type = htons (GNUNET_MESSAGE_TYPE_STREAM_CLOSE_ACK);
  queue_message (socket, close_ack, &set_state_closed, NULL, GNUNET_NO);
  if ((STATE_CLOSED == socket->state) || (STATE_CLOSE_WAIT == socket->state))
    return GNUNET_OK;
  if (GNUNET_NO == socket->transmit_closed)
    do_transmit_shutdown (socket);
  if (GNUNET_NO == socket->receive_closed)
    do_receive_shutdown (socket);
  return GNUNET_OK;
}


/**
 * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_CLOSE
 *
 * @param cls the socket (set from GNUNET_MESH_connect)
 * @param tunnel connection to the other end
 * @param tunnel_ctx this is NULL
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
client_handle_close (void *cls,
                     struct GNUNET_MESH_Tunnel *tunnel,
                     void **tunnel_ctx,
                     const struct GNUNET_PeerIdentity *sender,
                     const struct GNUNET_MessageHeader *message,
                     const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = cls;

  return handle_close (socket,
                       tunnel,
                       sender,
                       (const struct GNUNET_MessageHeader *) message,
                       atsi);
}


/**
 * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_CLOSE_ACK
 *
 * @param cls the socket (set from GNUNET_MESH_connect)
 * @param tunnel connection to the other end
 * @param tunnel_ctx this is NULL
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
client_handle_close_ack (void *cls,
                         struct GNUNET_MESH_Tunnel *tunnel,
                         void **tunnel_ctx,
                         const struct GNUNET_PeerIdentity *sender,
                         const struct GNUNET_MessageHeader *message,
                         const struct GNUNET_ATS_Information *atsi)
{
  struct GNUNET_STREAM_Socket *socket = cls;

  return handle_generic_close_ack (socket,
                                   tunnel,
                                   sender,
                                   (const struct GNUNET_MessageHeader *) 
                                   message,
                                   atsi,
                                   SHUT_RDWR);
}

/*****************************/
/* Server's Message Handlers */
/*****************************/

/**
 * Server's message Handler for GNUNET_MESSAGE_TYPE_STREAM_DATA
 *
 * @param cls the closure
 * @param tunnel connection to the other end
 * @param tunnel_ctx the socket
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
server_handle_data (void *cls,
                    struct GNUNET_MESH_Tunnel *tunnel,
                    void **tunnel_ctx,
                    const struct GNUNET_PeerIdentity *sender,
                    const struct GNUNET_MessageHeader *message,
                    const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;

  return handle_data (socket,
                      tunnel,
                      sender,
                      (const struct GNUNET_STREAM_DataMessage *)message,
                      atsi);
}


/**
 * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_HELLO
 *
 * @param cls the closure
 * @param tunnel connection to the other end
 * @param tunnel_ctx the socket
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
server_handle_hello (void *cls,
                     struct GNUNET_MESH_Tunnel *tunnel,
                     void **tunnel_ctx,
                     const struct GNUNET_PeerIdentity *sender,
                     const struct GNUNET_MessageHeader *message,
                     const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
  const struct GNUNET_STREAM_HelloMessage *hello;
  struct GNUNET_STREAM_HelloAckMessage *reply;
  uint32_t port;

  hello = (const struct GNUNET_STREAM_HelloMessage *) message;
  if (0 != memcmp (sender,
                   &socket->other_peer,
                   sizeof (struct GNUNET_PeerIdentity)))
  {
    LOG_DEBUG ("%s: Received HELLO from non-confirming peer\n",
               GNUNET_i2s (&socket->other_peer));
    return GNUNET_YES;
  }
  GNUNET_assert (GNUNET_MESSAGE_TYPE_STREAM_HELLO == ntohs (message->type));
  GNUNET_assert (socket->tunnel == tunnel);
  LOG_DEBUG ("%1$s: Received HELLO from %1$s\n", 
             GNUNET_i2s (&socket->other_peer));
  port = (uint32_t) GNUNET_ntohll (hello->port);
  switch (socket->state)
  {
  case STATE_INIT:
    if (port != socket->port)
    {
      LOG_DEBUG ("Ignoring HELLO for port %u\n", port);
      GNUNET_MESH_tunnel_destroy (tunnel);
      GNUNET_free (socket);
      return GNUNET_OK;
    }
    reply = generate_hello_ack (socket, GNUNET_YES);
    queue_message (socket, &reply->header, &set_state_hello_wait, NULL,
                   GNUNET_NO);
    GNUNET_assert (GNUNET_SCHEDULER_NO_TASK ==
                   socket->control_retransmission_task_id);
    socket->control_retransmission_task_id =
      GNUNET_SCHEDULER_add_delayed (socket->retransmit_timeout,
                                    &control_retransmission_task, socket);
    break;
  case STATE_HELLO_WAIT:
    /* Perhaps our HELLO_ACK was lost */
    GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != 
                   socket->control_retransmission_task_id);
    GNUNET_SCHEDULER_cancel (socket->control_retransmission_task_id);
    socket->control_retransmission_task_id =
      GNUNET_SCHEDULER_add_now (&control_retransmission_task, socket);
    break;
  default:
    LOG_DEBUG( "%s: Client sent HELLO when in state %d\n",
               GNUNET_i2s (&socket->other_peer), socket->state);
    /* FIXME: Send RESET? */
  }
  return GNUNET_OK;
}


/**
 * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK
 *
 * @param cls the closure
 * @param tunnel connection to the other end
 * @param tunnel_ctx the socket
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
server_handle_hello_ack (void *cls,
                         struct GNUNET_MESH_Tunnel *tunnel,
                         void **tunnel_ctx,
                         const struct GNUNET_PeerIdentity *sender,
                         const struct GNUNET_MessageHeader *message,
                         const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
  const struct GNUNET_STREAM_HelloAckMessage *ack_message;

  GNUNET_assert (GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK ==
                 ntohs (message->type));
  GNUNET_assert (socket->tunnel == tunnel);
  ack_message = (struct GNUNET_STREAM_HelloAckMessage *) message;
  switch (socket->state)  
  {
  case STATE_HELLO_WAIT:
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Received HELLO_ACK from %s\n",
         GNUNET_i2s (&socket->other_peer),
         GNUNET_i2s (&socket->other_peer));
    socket->read_sequence_number = ntohl (ack_message->sequence_number);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Read sequence number %u\n",
         GNUNET_i2s (&socket->other_peer),
         (unsigned int) socket->read_sequence_number);
    socket->receiver_window_available = 
      ntohl (ack_message->receiver_window_size);
    set_state_established (NULL, socket);
    break;
  default:
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Client sent HELLO_ACK when in state %d\n", socket->state);    
  }
  return GNUNET_OK;
}


/**
 * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_RESET
 *
 * @param cls the closure
 * @param tunnel connection to the other end
 * @param tunnel_ctx the socket
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
server_handle_reset (void *cls,
                     struct GNUNET_MESH_Tunnel *tunnel,
                     void **tunnel_ctx,
                     const struct GNUNET_PeerIdentity *sender,
                     const struct GNUNET_MessageHeader *message,
                     const struct GNUNET_ATS_Information*atsi)
{
  // struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
  /* FIXME */
  return GNUNET_OK;
}


/**
 * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE
 *
 * @param cls the closure
 * @param tunnel connection to the other end
 * @param tunnel_ctx the socket
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
server_handle_transmit_close (void *cls,
                              struct GNUNET_MESH_Tunnel *tunnel,
                              void **tunnel_ctx,
                              const struct GNUNET_PeerIdentity *sender,
                              const struct GNUNET_MessageHeader *message,
                              const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;

  return handle_transmit_close (socket, tunnel, sender, message, atsi);
}


/**
 * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE_ACK
 *
 * @param cls the closure
 * @param tunnel connection to the other end
 * @param tunnel_ctx the socket
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
server_handle_transmit_close_ack (void *cls,
                                  struct GNUNET_MESH_Tunnel *tunnel,
                                  void **tunnel_ctx,
                                  const struct GNUNET_PeerIdentity *sender,
                                  const struct GNUNET_MessageHeader *message,
                                  const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;

  return handle_generic_close_ack (socket, tunnel, sender, message, atsi,
                                   SHUT_WR);
}


/**
 * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE
 *
 * @param cls the closure
 * @param tunnel connection to the other end
 * @param tunnel_ctx the socket
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
server_handle_receive_close (void *cls,
                             struct GNUNET_MESH_Tunnel *tunnel,
                             void **tunnel_ctx,
                             const struct GNUNET_PeerIdentity *sender,
                             const struct GNUNET_MessageHeader *message,
                             const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;

  return handle_receive_close (socket, tunnel, sender, message, atsi);
}


/**
 * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE_ACK
 *
 * @param cls the closure
 * @param tunnel connection to the other end
 * @param tunnel_ctx the socket
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
server_handle_receive_close_ack (void *cls,
                                 struct GNUNET_MESH_Tunnel *tunnel,
                                 void **tunnel_ctx,
                                 const struct GNUNET_PeerIdentity *sender,
                                 const struct GNUNET_MessageHeader *message,
                                 const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;

  return handle_generic_close_ack (socket, tunnel, sender, message, atsi,
                                   SHUT_RD);
}


/**
 * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_CLOSE
 *
 * @param cls the listen socket (from GNUNET_MESH_connect in
 *          GNUNET_STREAM_listen) 
 * @param tunnel connection to the other end
 * @param tunnel_ctx the socket
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
server_handle_close (void *cls,
                     struct GNUNET_MESH_Tunnel *tunnel,
                     void **tunnel_ctx,
                     const struct GNUNET_PeerIdentity *sender,
                     const struct GNUNET_MessageHeader *message,
                     const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
  
  return handle_close (socket, tunnel, sender, message, atsi);
}


/**
 * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_CLOSE_ACK
 *
 * @param cls the closure
 * @param tunnel connection to the other end
 * @param tunnel_ctx the socket
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
server_handle_close_ack (void *cls,
                         struct GNUNET_MESH_Tunnel *tunnel,
                         void **tunnel_ctx,
                         const struct GNUNET_PeerIdentity *sender,
                         const struct GNUNET_MessageHeader *message,
                         const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;

  return handle_generic_close_ack (socket, tunnel, sender, message, atsi,
                                   SHUT_RDWR);
}


/**
 * Handler for DATA_ACK messages
 *
 * @param socket the socket through which the ack was received
 * @param tunnel connection to the other end
 * @param sender who sent the message
 * @param ack the acknowledgment message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
handle_ack (struct GNUNET_STREAM_Socket *socket,
	    struct GNUNET_MESH_Tunnel *tunnel,
	    const struct GNUNET_PeerIdentity *sender,
	    const struct GNUNET_STREAM_AckMessage *ack,
	    const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_WriteHandle *write_handle;
  uint64_t ack_bitmap;
  unsigned int packet;
  int need_retransmission;
  uint32_t sequence_difference;

  if (0 != memcmp (sender,
                   &socket->other_peer,
                   sizeof (struct GNUNET_PeerIdentity)))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Received ACK from non-confirming peer\n",
         GNUNET_i2s (&socket->other_peer));
    return GNUNET_YES;
  }
  switch (socket->state)
  {
  case (STATE_ESTABLISHED):
  case (STATE_RECEIVE_CLOSED):
  case (STATE_RECEIVE_CLOSE_WAIT):
    if (NULL == socket->write_handle)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "%s: Received DATA_ACK when write_handle is NULL\n",
           GNUNET_i2s (&socket->other_peer));
      return GNUNET_OK;
    }
    sequence_difference = 
	socket->write_sequence_number - ntohl (ack->base_sequence_number);
    if (!(sequence_difference <= GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "%s: Received DATA_ACK with unexpected base sequence number\n",
           GNUNET_i2s (&socket->other_peer));
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "%s: Current write sequence: %u; Ack's base sequence: %u\n",
           GNUNET_i2s (&socket->other_peer),
           socket->write_sequence_number,
           ntohl (ack->base_sequence_number));
      return GNUNET_OK;
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: Received DATA_ACK from %s\n",
         GNUNET_i2s (&socket->other_peer), GNUNET_i2s (&socket->other_peer));
    /* Cancel the retransmission task */
    if (GNUNET_SCHEDULER_NO_TASK != socket->data_retransmission_task_id)
    {
      GNUNET_SCHEDULER_cancel (socket->data_retransmission_task_id);
      socket->data_retransmission_task_id = GNUNET_SCHEDULER_NO_TASK;
      socket->data_retransmit_timeout = GNUNET_TIME_UNIT_SECONDS;
    }
    for (packet=0; packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH; packet++)
    {
      if (NULL == socket->write_handle->messages[packet])
        break;
      /* BS: Base sequence from ack; PS: sequence num of current packet */
      sequence_difference = ntohl (ack->base_sequence_number)
        - ntohl (socket->write_handle->messages[packet]->sequence_number);
      if (0 == sequence_difference)
	break; /* The message in our handle is not yet received */
      /* case where BS = PS + GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH */
      /* sequence_difference <= GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH */
      ackbitmap_modify_bit (&socket->write_handle->ack_bitmap,
			    packet, GNUNET_YES);
    }
    if (((ntohl (ack->base_sequence_number)
         - (socket->write_handle->max_ack_base_num))
          <= GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH))
    {
      socket->write_handle->max_ack_base_num = ntohl (ack->base_sequence_number);
      socket->receiver_window_available = 
          ntohl (ack->receive_window_remaining);
    }
    else
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Ignoring to modify receive window available as base: %u, max_ack_base: %u\n",
                  ntohl (ack->base_sequence_number),
                   socket->write_handle->max_ack_base_num);
    if ((packet == GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH)
        || ((packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH)
            && (NULL == socket->write_handle->messages[packet])))
      goto call_write_cont_cb;
    GNUNET_assert (ntohl
                   (socket->write_handle->messages[packet]->sequence_number)
                   == ntohl (ack->base_sequence_number));
    /* Update our bitmap */
    ack_bitmap = GNUNET_ntohll (ack->bitmap);
    for (; packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH; packet++)
    {
      if (NULL == socket->write_handle->messages[packet]) break;
      if (ackbitmap_is_bit_set (&ack_bitmap, ntohl
                                (socket->write_handle->messages[packet]->sequence_number)
                                - ntohl (ack->base_sequence_number)))
        ackbitmap_modify_bit (&socket->write_handle->ack_bitmap, packet, GNUNET_YES);
    }
    /* Check if we have received all acknowledgements */
    need_retransmission = GNUNET_NO;
    for (packet=0; packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH; packet++)
    {
      if (NULL == socket->write_handle->messages[packet]) break;
      if (GNUNET_YES != ackbitmap_is_bit_set 
          (&socket->write_handle->ack_bitmap,packet))
      {
        need_retransmission = GNUNET_YES;
        break;
      }
    }
    if (GNUNET_YES == need_retransmission)
    {
      write_data (socket);
      return GNUNET_OK;
    }

  call_write_cont_cb:
    /* Free the packets */
    for (packet=0; packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH; packet++)
    {
      GNUNET_free_non_null (socket->write_handle->messages[packet]);
    }
    write_handle = socket->write_handle;
    socket->write_handle = NULL;
    if (NULL != write_handle->write_cont)
      write_handle->write_cont (write_handle->write_cont_cls,
                                GNUNET_STREAM_OK,
                                write_handle->size);
    /* We are done with the write handle - Freeing it */
    GNUNET_free (write_handle);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: Write completion callback completed\n",
         GNUNET_i2s (&socket->other_peer));      
    break;
  default:
    break;
  }
  return GNUNET_OK;
}


/**
 * Handler for DATA_ACK messages
 *
 * @param cls the 'struct GNUNET_STREAM_Socket'
 * @param tunnel connection to the other end
 * @param tunnel_ctx unused
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
client_handle_ack (void *cls,
		   struct GNUNET_MESH_Tunnel *tunnel,
		   void **tunnel_ctx,
		   const struct GNUNET_PeerIdentity *sender,
		   const struct GNUNET_MessageHeader *message,
		   const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = cls;
  const struct GNUNET_STREAM_AckMessage *ack;

  ack = (const struct GNUNET_STREAM_AckMessage *) message; 
  return handle_ack (socket, tunnel, sender, ack, atsi);
}


/**
 * Handler for DATA_ACK messages
 *
 * @param cls the server's listen socket
 * @param tunnel connection to the other end
 * @param tunnel_ctx pointer to the 'struct GNUNET_STREAM_Socket*'
 * @param sender who sent the message
 * @param message the actual message
 * @param atsi performance data for the connection
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
static int
server_handle_ack (void *cls,
		   struct GNUNET_MESH_Tunnel *tunnel,
		   void **tunnel_ctx,
		   const struct GNUNET_PeerIdentity *sender,
		   const struct GNUNET_MessageHeader *message,
		   const struct GNUNET_ATS_Information*atsi)
{
  struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
  const struct GNUNET_STREAM_AckMessage *ack = (const struct GNUNET_STREAM_AckMessage *) message;
 
  return handle_ack (socket, tunnel, sender, ack, atsi);
}


/**
 * For client message handlers, the stream socket is in the
 * closure argument.
 */
static struct GNUNET_MESH_MessageHandler client_message_handlers[] = {
  {&client_handle_data, GNUNET_MESSAGE_TYPE_STREAM_DATA, 0},
  {&client_handle_ack, GNUNET_MESSAGE_TYPE_STREAM_ACK, 
   sizeof (struct GNUNET_STREAM_AckMessage) },
  {&client_handle_hello_ack, GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK,
   sizeof (struct GNUNET_STREAM_HelloAckMessage)},
  {&client_handle_reset, GNUNET_MESSAGE_TYPE_STREAM_RESET,
   sizeof (struct GNUNET_MessageHeader)},
  {&client_handle_transmit_close, GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE,
   sizeof (struct GNUNET_MessageHeader)},
  {&client_handle_transmit_close_ack, GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE_ACK,
   sizeof (struct GNUNET_MessageHeader)},
  {&client_handle_receive_close, GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE,
   sizeof (struct GNUNET_MessageHeader)},
  {&client_handle_receive_close_ack, GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE_ACK,
   sizeof (struct GNUNET_MessageHeader)},
  {&client_handle_close, GNUNET_MESSAGE_TYPE_STREAM_CLOSE,
   sizeof (struct GNUNET_MessageHeader)},
  {&client_handle_close_ack, GNUNET_MESSAGE_TYPE_STREAM_CLOSE_ACK,
   sizeof (struct GNUNET_MessageHeader)},
  {NULL, 0, 0}
};


/**
 * For server message handlers, the stream socket is in the
 * tunnel context, and the listen socket in the closure argument.
 */
static struct GNUNET_MESH_MessageHandler server_message_handlers[] = {
  {&server_handle_data, GNUNET_MESSAGE_TYPE_STREAM_DATA, 0},
  {&server_handle_ack, GNUNET_MESSAGE_TYPE_STREAM_ACK, 
   sizeof (struct GNUNET_STREAM_AckMessage) },
  {&server_handle_hello, GNUNET_MESSAGE_TYPE_STREAM_HELLO, 
   sizeof (struct GNUNET_STREAM_HelloMessage)},
  {&server_handle_hello_ack, GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK,
   sizeof (struct GNUNET_STREAM_HelloAckMessage)},
  {&server_handle_reset, GNUNET_MESSAGE_TYPE_STREAM_RESET,
   sizeof (struct GNUNET_MessageHeader)},
  {&server_handle_transmit_close, GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE,
   sizeof (struct GNUNET_MessageHeader)},
  {&server_handle_transmit_close_ack, GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE_ACK,
   sizeof (struct GNUNET_MessageHeader)},
  {&server_handle_receive_close, GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE,
   sizeof (struct GNUNET_MessageHeader)},
  {&server_handle_receive_close_ack, GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE_ACK,
   sizeof (struct GNUNET_MessageHeader)},
  {&server_handle_close, GNUNET_MESSAGE_TYPE_STREAM_CLOSE,
   sizeof (struct GNUNET_MessageHeader)},
  {&server_handle_close_ack, GNUNET_MESSAGE_TYPE_STREAM_CLOSE_ACK,
   sizeof (struct GNUNET_MessageHeader)},
  {NULL, 0, 0}
};


/**
 * Function called when our target peer is connected to our tunnel
 *
 * @param cls the socket for which this tunnel is created
 * @param peer the peer identity of the target
 * @param atsi performance data for the connection
 */
static void
mesh_peer_connect_callback (void *cls,
                            const struct GNUNET_PeerIdentity *peer,
                            const struct GNUNET_ATS_Information * atsi)
{
  struct GNUNET_STREAM_Socket *socket = cls;
  struct GNUNET_MessageHeader *message;
  
  if (0 != memcmp (peer,
                   &socket->other_peer,
                   sizeof (struct GNUNET_PeerIdentity)))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: A peer which is not our target has connected to our tunnel\n",
         GNUNET_i2s(peer));
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s: Target peer %s connected\n",
       GNUNET_i2s (&socket->other_peer),
       GNUNET_i2s (&socket->other_peer));
  /* Set state to INIT */
  socket->state = STATE_INIT;
  /* Send HELLO message */
  message = generate_hello (socket);
  queue_message (socket, message, &set_state_hello_wait, NULL, GNUNET_NO);
  if (GNUNET_SCHEDULER_NO_TASK != socket->control_retransmission_task_id)
    GNUNET_SCHEDULER_cancel (socket->control_retransmission_task_id);
  socket->control_retransmission_task_id =
    GNUNET_SCHEDULER_add_delayed (socket->retransmit_timeout,
                                  &control_retransmission_task, socket);
}


/**
 * Function called when our target peer is disconnected from our tunnel
 *
 * @param cls the socket associated which this tunnel
 * @param peer the peer identity of the target
 */
static void
mesh_peer_disconnect_callback (void *cls,
                               const struct GNUNET_PeerIdentity *peer)
{
  struct GNUNET_STREAM_Socket *socket=cls;
  
  /* If the state is SHUTDOWN its ok; else set the state of the socket to SYSERR */
  LOG_DEBUG ("%1$s: Other peer %1$s disconnected \n",
             GNUNET_i2s (&socket->other_peer));
}


/**
 * Method called whenever a peer creates a tunnel to us
 *
 * @param cls closure
 * @param tunnel new handle to the tunnel
 * @param initiator peer that started the tunnel
 * @param atsi performance information for the tunnel
 * @return initial tunnel context for the tunnel
 *         (can be NULL -- that's not an error)
 */
static void *
new_tunnel_notify (void *cls,
                   struct GNUNET_MESH_Tunnel *tunnel,
                   const struct GNUNET_PeerIdentity *initiator,
                   const struct GNUNET_ATS_Information *atsi)
{
  struct GNUNET_STREAM_ListenSocket *lsocket = cls;
  struct GNUNET_STREAM_Socket *socket;

  /* FIXME: If a tunnel is already created, we should not accept new tunnels
     from the same peer again until the socket is closed */
  if (GNUNET_NO == lsocket->listening)
  {
    GNUNET_MESH_tunnel_destroy (tunnel);
    return NULL;
  }
  socket = GNUNET_malloc (sizeof (struct GNUNET_STREAM_Socket));
  socket->other_peer = *initiator;
  socket->tunnel = tunnel;
  socket->state = STATE_INIT;
  socket->lsocket = lsocket;
  socket->port = lsocket->port;
  socket->stat_handle = lsocket->stat_handle;
  socket->retransmit_timeout = lsocket->retransmit_timeout;
  socket->testing_active = lsocket->testing_active;
  socket->testing_set_write_sequence_number_value =
      lsocket->testing_set_write_sequence_number_value;
  socket->max_payload_size = lsocket->max_payload_size;
  LOG_DEBUG ("%1$s: Peer %1$s initiated tunnel to us\n",
             GNUNET_i2s (&socket->other_peer));
  if (NULL != socket->stat_handle)
  {
    GNUNET_STATISTICS_update (socket->stat_handle,
                              "total inbound connections received",
                              1, GNUNET_NO);
    GNUNET_STATISTICS_update (socket->stat_handle,
                              "inbound connections", 1, GNUNET_NO);
  }
  return socket;
}


/**
 * Function called whenever an inbound tunnel is destroyed.  Should clean up
 * any associated state.  This function is NOT called if the client has
 * explicitly asked for the tunnel to be destroyed using
 * GNUNET_MESH_tunnel_destroy. It must NOT call GNUNET_MESH_tunnel_destroy on
 * the tunnel.
 *
 * @param cls closure (set from GNUNET_MESH_connect)
 * @param tunnel connection to the other end (henceforth invalid)
 * @param tunnel_ctx place where local state associated
 *                   with the tunnel is stored
 */
static void 
tunnel_cleaner (void *cls,
                const struct GNUNET_MESH_Tunnel *tunnel,
                void *tunnel_ctx)
{
  struct GNUNET_STREAM_Socket *socket = tunnel_ctx;
  struct MessageQueue *head;

  GNUNET_assert (tunnel == socket->tunnel);
  GNUNET_break_op(0);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s: Peer %s has terminated connection abruptly\n",
       GNUNET_i2s (&socket->other_peer),
       GNUNET_i2s (&socket->other_peer));
  if (NULL != socket->stat_handle)
  {
    GNUNET_STATISTICS_update (socket->stat_handle,
                              "connections terminated abruptly", 1, GNUNET_NO);
    GNUNET_STATISTICS_update (socket->stat_handle,
                              "inbound connections", -1, GNUNET_NO);
  }
  /* Clear Transmit handles */
  if (NULL != socket->transmit_handle)
  {
    GNUNET_MESH_notify_transmit_ready_cancel (socket->transmit_handle);
    socket->transmit_handle = NULL;
  }
  /* Stop Tasks using socket->tunnel */
  if (GNUNET_SCHEDULER_NO_TASK != socket->ack_task_id)
  {
    GNUNET_SCHEDULER_cancel (socket->ack_task_id);
    socket->ack_task_id = GNUNET_SCHEDULER_NO_TASK;
  }
  if (GNUNET_SCHEDULER_NO_TASK != socket->data_retransmission_task_id)
  {
    GNUNET_SCHEDULER_cancel (socket->data_retransmission_task_id);
    socket->data_retransmission_task_id = GNUNET_SCHEDULER_NO_TASK;
  }  
  /* Terminate the control retransmission tasks */
  if (GNUNET_SCHEDULER_NO_TASK != socket->control_retransmission_task_id)
  {
    GNUNET_SCHEDULER_cancel (socket->control_retransmission_task_id);
    socket->control_retransmission_task_id = GNUNET_SCHEDULER_NO_TASK;
  }
  /* Clear existing message queue */
  while (NULL != (head = socket->queue_head)) {
    GNUNET_CONTAINER_DLL_remove (socket->queue_head,
				 socket->queue_tail,
				 head);
    GNUNET_free (head->message);
    GNUNET_free (head);
  }
  socket->tunnel = NULL;
}


/**
 * Callback to signal timeout on lockmanager lock acquire
 *
 * @param cls the ListenSocket
 * @param tc the scheduler task context
 */
static void
lockmanager_acquire_timeout (void *cls, 
                             const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_STREAM_ListenSocket *lsocket = cls;
  GNUNET_STREAM_ListenCallback listen_cb;
  void *listen_cb_cls;

  lsocket->lockmanager_acquire_timeout_task = GNUNET_SCHEDULER_NO_TASK;
  listen_cb = lsocket->listen_cb;
  listen_cb_cls = lsocket->listen_cb_cls;
  if (NULL != listen_cb)
    listen_cb (listen_cb_cls, NULL, NULL);
}


/**
 * Callback to notify us on the status changes on app_port lock
 *
 * @param cls the ListenSocket
 * @param domain the domain name of the lock
 * @param lock the app_port
 * @param status the current status of the lock
 */
static void
lock_status_change_cb (void *cls, const char *domain, uint32_t lock,
                       enum GNUNET_LOCKMANAGER_Status status)
{
  struct GNUNET_STREAM_ListenSocket *lsocket = cls;

  GNUNET_assert (lock == (uint32_t) lsocket->port);
  if (GNUNET_LOCKMANAGER_SUCCESS == status)
  {
    lsocket->listening = GNUNET_YES;
    if (GNUNET_SCHEDULER_NO_TASK != lsocket->lockmanager_acquire_timeout_task)
    {
      GNUNET_SCHEDULER_cancel (lsocket->lockmanager_acquire_timeout_task);
      lsocket->lockmanager_acquire_timeout_task = GNUNET_SCHEDULER_NO_TASK;
    }
    if (NULL == lsocket->mesh)
    {
      GNUNET_MESH_ApplicationType ports[] = {lsocket->port, 0};

      lsocket->mesh = GNUNET_MESH_connect (lsocket->cfg,
                                           lsocket, /* Closure */
                                           &new_tunnel_notify,
                                           &tunnel_cleaner,
                                           server_message_handlers,
                                           ports);
      GNUNET_assert (NULL != lsocket->mesh);
      if (NULL != lsocket->listen_ok_cb)
      {
        (void) lsocket->listen_ok_cb ();
      }
    }
  }
  if (GNUNET_LOCKMANAGER_RELEASE == status)
    lsocket->listening = GNUNET_NO;
}


/*****************/
/* API functions */
/*****************/


/**
 * Tries to open a stream to the target peer
 *
 * @param cfg configuration to use
 * @param target the target peer to which the stream has to be opened
 * @param app_port the application port number which uniquely identifies this
 *            stream
 * @param open_cb this function will be called after stream has be established;
 *          cannot be NULL
 * @param open_cb_cls the closure for open_cb
 * @param ... options to the stream, terminated by GNUNET_STREAM_OPTION_END
 * @return if successful it returns the stream socket; NULL if stream cannot be
 *         opened 
 */
struct GNUNET_STREAM_Socket *
GNUNET_STREAM_open (const struct GNUNET_CONFIGURATION_Handle *cfg,
                    const struct GNUNET_PeerIdentity *target,
                    GNUNET_MESH_ApplicationType app_port,
                    GNUNET_STREAM_OpenCallback open_cb,
                    void *open_cb_cls,
                    ...)
{
  struct GNUNET_STREAM_Socket *socket;
  enum GNUNET_STREAM_Option option;
  va_list vargs;
  uint16_t payload_size;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s\n", __func__);
  GNUNET_assert (NULL != open_cb);
  socket = GNUNET_malloc (sizeof (struct GNUNET_STREAM_Socket));
  socket->other_peer = *target;
  socket->open_cb = open_cb;
  socket->open_cls = open_cb_cls;
  socket->port = app_port;
  /* Set defaults */
  socket->retransmit_timeout = TIME_REL_SECS (default_timeout);
  socket->testing_active = GNUNET_NO;
  socket->max_payload_size = DEFAULT_MAX_PAYLOAD_SIZE;
  va_start (vargs, open_cb_cls); /* Parse variable args */
  do {
    option = va_arg (vargs, enum GNUNET_STREAM_Option);
    switch (option)
    {
    case GNUNET_STREAM_OPTION_INITIAL_RETRANSMIT_TIMEOUT:
      /* Expect struct GNUNET_TIME_Relative */
      socket->retransmit_timeout = va_arg (vargs,
                                           struct GNUNET_TIME_Relative);
      break;
    case GNUNET_STREAM_OPTION_TESTING_SET_WRITE_SEQUENCE_NUMBER:
      socket->testing_active = GNUNET_YES;
      socket->testing_set_write_sequence_number_value = va_arg (vargs,
                                                                uint32_t);
      break;
    case GNUNET_STREAM_OPTION_LISTEN_TIMEOUT:
      GNUNET_break (0);          /* Option irrelevant in STREAM_open */
      break;
    case GNUNET_STREAM_OPTION_SIGNAL_LISTEN_SUCCESS:
      GNUNET_break (0);          /* Option irrelevant in STREAM_open */
      break;
    case GNUNET_STREAM_OPTION_MAX_PAYLOAD_SIZE:
      payload_size = (uint16_t) va_arg (vargs, unsigned int);
      GNUNET_assert (0 != payload_size);
      if (payload_size < socket->max_payload_size)
	socket->max_payload_size = payload_size;
      break;
    case GNUNET_STREAM_OPTION_END:
      break;
    }
  } while (GNUNET_STREAM_OPTION_END != option);
  va_end (vargs);               /* End of variable args parsing */
  socket->mesh = GNUNET_MESH_connect (cfg, /* the configuration handle */
                                      socket, /* cls */
                                      NULL, /* No inbound tunnel handler */
                                      NULL, /* No in-tunnel cleaner */
                                      client_message_handlers,
                                      NULL); /* We don't get inbound tunnels */
  if (NULL == socket->mesh)   /* Fail if we cannot connect to mesh */
  {
    GNUNET_free (socket);
    return NULL;
  }
  /* Now create the mesh tunnel to target */
  LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating MESH Tunnel\n");
  socket->tunnel = GNUNET_MESH_tunnel_create (socket->mesh,
                                              NULL, /* Tunnel context */
                                              &mesh_peer_connect_callback,
                                              &mesh_peer_disconnect_callback,
                                              socket);
  GNUNET_assert (NULL != socket->tunnel);
  GNUNET_MESH_peer_request_connect_add (socket->tunnel,
                                        &socket->other_peer);
  socket->stat_handle = GNUNET_STATISTICS_create ("stream", cfg);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "%s() END\n", __func__);
  return socket;
}


/**
 * Shutdown the stream for reading or writing (similar to man 2 shutdown).
 *
 * @param socket the stream socket
 * @param operation SHUT_RD, SHUT_WR or SHUT_RDWR
 * @param completion_cb the callback that will be called upon successful
 *          shutdown of given operation
 * @param completion_cls the closure for the completion callback
 * @return the shutdown handle
 */
struct GNUNET_STREAM_ShutdownHandle *
GNUNET_STREAM_shutdown (struct GNUNET_STREAM_Socket *socket,
			int operation,
                        GNUNET_STREAM_ShutdownCompletion completion_cb,
                        void *completion_cls)
{
  struct GNUNET_STREAM_ShutdownHandle *handle;
  struct GNUNET_MessageHeader *msg;
  
  GNUNET_assert (NULL == socket->shutdown_handle);
  handle = GNUNET_malloc (sizeof (struct GNUNET_STREAM_ShutdownHandle));
  handle->socket = socket;
  handle->completion_cb = completion_cb;
  handle->completion_cls = completion_cls;
  socket->shutdown_handle = handle;
  if ( ((GNUNET_YES == socket->receive_closed) && (SHUT_RD == operation))
       || ((GNUNET_YES == socket->transmit_closed) && (SHUT_WR == operation))
       || ((GNUNET_YES == socket->transmit_closed) 
           && (GNUNET_YES == socket->receive_closed)
           && (SHUT_RDWR == operation)) )
  {
    handle->operation = operation;
    handle->call_cont_task_id = GNUNET_SCHEDULER_add_now (&call_cont_task,
                                                          socket);
    return handle;
  }
  msg = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader));
  msg->size = htons (sizeof (struct GNUNET_MessageHeader));
  switch (operation)
  {
  case SHUT_RD:
    handle->operation = SHUT_RD;
    if (NULL != socket->read_handle)
      LOG (GNUNET_ERROR_TYPE_WARNING,
           "Existing read handle should be cancelled before shutting"
           " down reading\n");
    msg->type = htons (GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE);
    queue_message (socket, msg, &set_state_receive_close_wait, NULL,
                   GNUNET_NO);
    socket->receive_closed = GNUNET_YES;
    break;
  case SHUT_WR:
    handle->operation = SHUT_WR;
    if (NULL != socket->write_handle)
      LOG (GNUNET_ERROR_TYPE_WARNING,
           "Existing write handle should be cancelled before shutting"
           " down writing\n");
    msg->type = htons (GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE);
    queue_message (socket, msg, &set_state_transmit_close_wait, NULL,
                   GNUNET_NO);
    socket->transmit_closed = GNUNET_YES;
    break;
  case SHUT_RDWR:
    handle->operation = SHUT_RDWR;
    if (NULL != socket->write_handle)
      LOG (GNUNET_ERROR_TYPE_WARNING,
           "Existing write handle should be cancelled before shutting"
           " down writing\n");
    if (NULL != socket->read_handle)
      LOG (GNUNET_ERROR_TYPE_WARNING,
           "Existing read handle should be cancelled before shutting"
           " down reading\n");
    msg->type = htons (GNUNET_MESSAGE_TYPE_STREAM_CLOSE);
    queue_message (socket, msg, &set_state_close_wait, NULL, GNUNET_NO);
    socket->transmit_closed = GNUNET_YES;
    socket->receive_closed = GNUNET_YES;
    break;
  default:
    LOG (GNUNET_ERROR_TYPE_WARNING,
         "GNUNET_STREAM_shutdown called with invalid value for "
         "parameter operation -- Ignoring\n");
    GNUNET_free (msg);
    GNUNET_free (handle);
    return NULL;
  }
  handle->close_msg_retransmission_task_id =
    GNUNET_SCHEDULER_add_delayed (socket->retransmit_timeout,
                                  &close_msg_retransmission_task,
                                  handle);
  return handle;
}


/**
 * Cancels a pending shutdown. Note that the shutdown messages may already be
 * sent and the stream is shutdown already for the operation given to
 * GNUNET_STREAM_shutdown(). This function only clears up any retranmissions of
 * shutdown messages and frees the shutdown handle.
 *
 * @param handle the shutdown handle returned from GNUNET_STREAM_shutdown
 */
void
GNUNET_STREAM_shutdown_cancel (struct GNUNET_STREAM_ShutdownHandle *handle)
{
  if (GNUNET_SCHEDULER_NO_TASK != handle->close_msg_retransmission_task_id)
    GNUNET_SCHEDULER_cancel (handle->close_msg_retransmission_task_id);
  if (GNUNET_SCHEDULER_NO_TASK != handle->call_cont_task_id)
    GNUNET_SCHEDULER_cancel (handle->call_cont_task_id);
  handle->socket->shutdown_handle = NULL;
  GNUNET_free (handle);
}


/**
 * Closes the stream
 *
 * @param socket the stream socket
 */
void
GNUNET_STREAM_close (struct GNUNET_STREAM_Socket *socket)
{
  struct MessageQueue *head;

  if (NULL != socket->read_handle)
  {
    LOG (GNUNET_ERROR_TYPE_WARNING,
	 "Closing STREAM socket when a read handle is pending\n");
    GNUNET_STREAM_read_cancel (socket->read_handle);
  }
  if (NULL != socket->write_handle)
  {
    LOG (GNUNET_ERROR_TYPE_WARNING,
	 "Closing STREAM socket when a write handle is pending\n");
    GNUNET_STREAM_write_cancel (socket->write_handle);
    //socket->write_handle = NULL;
  }
  /* Terminate the ack'ing task if they are still present */
  if (socket->ack_task_id != GNUNET_SCHEDULER_NO_TASK)
  {
    GNUNET_SCHEDULER_cancel (socket->ack_task_id);
    socket->ack_task_id = GNUNET_SCHEDULER_NO_TASK;
  }
  /* Terminate the control retransmission tasks */
  if (GNUNET_SCHEDULER_NO_TASK != socket->control_retransmission_task_id)
  {
    GNUNET_SCHEDULER_cancel (socket->control_retransmission_task_id);
  }
  /* Clear Transmit handles */
  if (NULL != socket->transmit_handle)
  {
    GNUNET_MESH_notify_transmit_ready_cancel (socket->transmit_handle);
    socket->transmit_handle = NULL;
  }
  /* Clear existing message queue */
  while (NULL != (head = socket->queue_head)) {
    GNUNET_CONTAINER_DLL_remove (socket->queue_head,
				 socket->queue_tail,
				 head);
    GNUNET_free (head->message);
    GNUNET_free (head);
  }
  /* Close associated tunnel */
  if (NULL != socket->tunnel)
  {
    GNUNET_MESH_tunnel_destroy (socket->tunnel);
    socket->tunnel = NULL;
  }
  /* Close mesh connection */
  if ((NULL != socket->mesh) && (NULL == socket->lsocket))
  {
    GNUNET_MESH_disconnect (socket->mesh);
    socket->mesh = NULL;
  }
  /* Close statistics connection */
  if ( (NULL != socket->stat_handle) && (NULL == socket->lsocket) )
    GNUNET_STATISTICS_destroy (socket->stat_handle, GNUNET_YES);
  /* Release receive buffer */
  if (NULL != socket->receive_buffer)
  {
    GNUNET_free (socket->receive_buffer);
  }
  GNUNET_free (socket);
}


/**
 * Listens for stream connections for a specific application ports
 *
 * @param cfg the configuration to use
 * @param app_port the application port for which new streams will be accepted
 * @param listen_cb this function will be called when a peer tries to establish
 *            a stream with us
 * @param listen_cb_cls closure for listen_cb
 * @param ... options to the stream, terminated by GNUNET_STREAM_OPTION_END
 * @return listen socket, NULL for any error
 */
struct GNUNET_STREAM_ListenSocket *
GNUNET_STREAM_listen (const struct GNUNET_CONFIGURATION_Handle *cfg,
                      GNUNET_MESH_ApplicationType app_port,
                      GNUNET_STREAM_ListenCallback listen_cb,
                      void *listen_cb_cls,
                      ...)
{
  struct GNUNET_STREAM_ListenSocket *lsocket;
  struct GNUNET_TIME_Relative listen_timeout;
  enum GNUNET_STREAM_Option option;
  va_list vargs;
  uint16_t payload_size;

  GNUNET_assert (NULL != listen_cb);
  lsocket = GNUNET_malloc (sizeof (struct GNUNET_STREAM_ListenSocket));
  lsocket->cfg = GNUNET_CONFIGURATION_dup (cfg);
  lsocket->lockmanager = GNUNET_LOCKMANAGER_connect (lsocket->cfg);
  if (NULL == lsocket->lockmanager)
  {
    GNUNET_CONFIGURATION_destroy (lsocket->cfg);
    GNUNET_free (lsocket);
    return NULL;
  }
  lsocket->listening = GNUNET_NO;/* We listen when we get a lock on app_port */  
  /* Set defaults */
  lsocket->retransmit_timeout = TIME_REL_SECS (default_timeout);
  lsocket->testing_active = GNUNET_NO;
  lsocket->listen_ok_cb = NULL;
  lsocket->max_payload_size = DEFAULT_MAX_PAYLOAD_SIZE;
  listen_timeout = TIME_REL_SECS (60); /* A minute for listen timeout */  
  va_start (vargs, listen_cb_cls);
  do {
    option = va_arg (vargs, enum GNUNET_STREAM_Option);
    switch (option)
    {
    case GNUNET_STREAM_OPTION_INITIAL_RETRANSMIT_TIMEOUT:
      lsocket->retransmit_timeout = va_arg (vargs,
                                            struct GNUNET_TIME_Relative);
      break;
    case GNUNET_STREAM_OPTION_TESTING_SET_WRITE_SEQUENCE_NUMBER:
      lsocket->testing_active = GNUNET_YES;
      lsocket->testing_set_write_sequence_number_value = va_arg (vargs,
                                                                 uint32_t);
      break;
    case GNUNET_STREAM_OPTION_LISTEN_TIMEOUT:
      listen_timeout = GNUNET_TIME_relative_multiply
        (GNUNET_TIME_UNIT_MILLISECONDS, va_arg (vargs, uint32_t));
      break;
    case GNUNET_STREAM_OPTION_SIGNAL_LISTEN_SUCCESS:
      lsocket->listen_ok_cb = va_arg (vargs,
                                      GNUNET_STREAM_ListenSuccessCallback);
      break;
    case GNUNET_STREAM_OPTION_MAX_PAYLOAD_SIZE:
      payload_size = (uint16_t) va_arg (vargs, unsigned int);
      GNUNET_assert (0 != payload_size);
      if (payload_size < lsocket->max_payload_size)
	lsocket->max_payload_size = payload_size;
      break;
    case GNUNET_STREAM_OPTION_END:
      break;
    }
  } while (GNUNET_STREAM_OPTION_END != option);
  va_end (vargs);
  lsocket->port = app_port;
  lsocket->listen_cb = listen_cb;
  lsocket->listen_cb_cls = listen_cb_cls;
  lsocket->locking_request = 
    GNUNET_LOCKMANAGER_acquire_lock (lsocket->lockmanager, locking_domain,
                                     (uint32_t) lsocket->port,
                                     &lock_status_change_cb, lsocket);
  lsocket->lockmanager_acquire_timeout_task =
    GNUNET_SCHEDULER_add_delayed (listen_timeout,
                                  &lockmanager_acquire_timeout, lsocket);
  lsocket->stat_handle = GNUNET_STATISTICS_create ("stream",
                                                   lsocket->cfg);
  return lsocket;
}


/**
 * Closes the listen socket
 *
 * @param lsocket the listen socket
 */
void
GNUNET_STREAM_listen_close (struct GNUNET_STREAM_ListenSocket *lsocket)
{
  /* Close MESH connection */
  if (NULL != lsocket->mesh)
    GNUNET_MESH_disconnect (lsocket->mesh);
  if (NULL != lsocket->stat_handle)
    GNUNET_STATISTICS_destroy (lsocket->stat_handle, GNUNET_YES);
  GNUNET_CONFIGURATION_destroy (lsocket->cfg);
  if (GNUNET_SCHEDULER_NO_TASK != lsocket->lockmanager_acquire_timeout_task)
    GNUNET_SCHEDULER_cancel (lsocket->lockmanager_acquire_timeout_task);
  if (NULL != lsocket->locking_request)
    GNUNET_LOCKMANAGER_cancel_request (lsocket->locking_request);
  if (NULL != lsocket->lockmanager)
    GNUNET_LOCKMANAGER_disconnect (lsocket->lockmanager);
  GNUNET_free (lsocket);
}


/**
 * Tries to write the given data to the stream. The maximum size of data that
 * can be written per a write operation is ~ 4MB (64 * (64000 - sizeof (struct
 * GNUNET_STREAM_DataMessage))). If size is greater than this it is not an API
 * violation, however only the said number of maximum bytes will be written.
 *
 * @param socket the socket representing a stream
 * @param data the data buffer from where the data is written into the stream
 * @param size the number of bytes to be written from the data buffer
 * @param timeout the timeout period
 * @param write_cont the function to call upon writing some bytes into the
 *          stream 
 * @param write_cont_cls the closure
 *
 * @return handle to cancel the operation; if a previous write is pending NULL
 *           is returned. If the stream has been shutdown for this operation or
 *           is broken then write_cont is immediately called and NULL is
 *           returned.
 */
struct GNUNET_STREAM_WriteHandle *
GNUNET_STREAM_write (struct GNUNET_STREAM_Socket *socket,
                     const void *data,
                     size_t size,
                     struct GNUNET_TIME_Relative timeout,
                     GNUNET_STREAM_CompletionContinuation write_cont,
                     void *write_cont_cls)
{
  struct GNUNET_STREAM_WriteHandle *io_handle;
  struct GNUNET_STREAM_DataMessage *dmsg;
  const void *sweep;
  struct GNUNET_TIME_Relative ack_deadline;
  unsigned int num_needed_packets;
  unsigned int cnt;
  uint32_t packet_size;
  uint32_t payload_size;
  uint16_t max_data_packet_size;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s\n", __func__);
  if (NULL != socket->write_handle)
  {
    GNUNET_break (0);
    return NULL;
  }
  if (NULL == socket->tunnel)
  {
    if (NULL != write_cont)
      write_cont (write_cont_cls, GNUNET_STREAM_SYSERR, 0);
    return NULL;
  }
  switch (socket->state)
  {
  case STATE_TRANSMIT_CLOSED:
  case STATE_TRANSMIT_CLOSE_WAIT:
  case STATE_CLOSED:
  case STATE_CLOSE_WAIT:
    if (NULL != write_cont)
      write_cont (write_cont_cls, GNUNET_STREAM_SHUTDOWN, 0);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s() END\n", __func__);
    return NULL;
  case STATE_INIT:
  case STATE_LISTEN:
  case STATE_HELLO_WAIT:
    if (NULL != write_cont)
      write_cont (write_cont_cls, GNUNET_STREAM_SYSERR, 0);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s() END\n", __func__);
    return NULL;
  case STATE_ESTABLISHED:
  case STATE_RECEIVE_CLOSED:
  case STATE_RECEIVE_CLOSE_WAIT:
    break;
  }
  if (GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH * socket->max_payload_size < size)
    size = GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH  * socket->max_payload_size;
  num_needed_packets =
      (size + (socket->max_payload_size - 1)) / socket->max_payload_size;
  io_handle = GNUNET_malloc (sizeof (struct GNUNET_STREAM_WriteHandle));
  io_handle->socket = socket;
  io_handle->write_cont = write_cont;
  io_handle->write_cont_cls = write_cont_cls;
  io_handle->size = size;
  io_handle->packets_sent = 0;
  sweep = data;
  /* FIXME: Remove the fixed delay for ack deadline; Set it to the value
     determined from RTT */
  ack_deadline = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5);
  /* Divide the given buffer into packets for sending */
  max_data_packet_size =
      socket->max_payload_size + sizeof (struct GNUNET_STREAM_DataMessage);
  io_handle->max_ack_base_num = socket->write_sequence_number;
  for (cnt=0; cnt < num_needed_packets; cnt++)
  {
    if ((cnt + 1) * socket->max_payload_size < size) 
    {
      payload_size = socket->max_payload_size;
      packet_size = max_data_packet_size;
    }
    else 
    {
      payload_size = size - (cnt * socket->max_payload_size);
      packet_size = payload_size + sizeof (struct GNUNET_STREAM_DataMessage);
    }
    dmsg = GNUNET_malloc (packet_size);    
    dmsg->header.size = htons (packet_size);
    dmsg->header.type = htons (GNUNET_MESSAGE_TYPE_STREAM_DATA);
    dmsg->sequence_number = htonl (socket->write_sequence_number++);
    dmsg->offset = htonl (socket->write_offset);
    /* FIXME: Remove the fixed delay for ack deadline; Set it to the value
       determined from RTT */
    dmsg->ack_deadline = GNUNET_TIME_relative_hton (ack_deadline);
    /* Copy data from given buffer to the packet */
    memcpy (&dmsg[1], sweep, payload_size);
    io_handle->messages[cnt] = dmsg;
    sweep += payload_size;
    socket->write_offset += payload_size;
  }
  /* ack the last data message. FIXME: remove when we figure out how to do this
     using RTT */
  io_handle->messages[num_needed_packets - 1]->ack_deadline = 
      GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_ZERO);
  socket->data_retransmit_timeout = GNUNET_TIME_UNIT_SECONDS;
  socket->write_handle = io_handle;
  write_data (socket);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s() END\n", __func__);
  return io_handle;
}


/**
 * Function to check the ACK bitmap for any received messages and call the data processor
 *
 * @param cls the socket
 * @param tc the scheduler task context
 */
static void
probe_data_availability (void *cls,
                         const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_STREAM_Socket *socket = cls;

  GNUNET_assert (NULL != socket->read_handle);
  socket->read_handle->probe_data_availability_task_id =
      GNUNET_SCHEDULER_NO_TASK;
  if (GNUNET_SCHEDULER_NO_TASK != socket->read_handle->read_task_id)
    return;     /* A task to call read processor is present */
  if (GNUNET_YES == ackbitmap_is_bit_set (&socket->ack_bitmap,
                                          0))
    socket->read_handle->read_task_id 
        = GNUNET_SCHEDULER_add_now (&call_read_processor, socket);
}


/**
 * Tries to read data from the stream. Should not be called when another read
 * handle is present; the existing read handle should be canceled with
 * GNUNET_STREAM_read_cancel(). Only one read handle per socket is present at
 * any time
 *
 * @param socket the socket representing a stream
 * @param timeout the timeout period
 * @param proc function to call with data (once only)
 * @param proc_cls the closure for proc
 * @return handle to cancel the operation; NULL is returned if the stream has
 *           been shutdown for this type of opeartion (the DataProcessor is
 *           immediately called with GNUNET_STREAM_SHUTDOWN as status)
 */
struct GNUNET_STREAM_ReadHandle *
GNUNET_STREAM_read (struct GNUNET_STREAM_Socket *socket,
                    struct GNUNET_TIME_Relative timeout,
		    GNUNET_STREAM_DataProcessor proc,
		    void *proc_cls)
{
  struct GNUNET_STREAM_ReadHandle *read_handle;
  
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s: %s()\n", 
       GNUNET_i2s (&socket->other_peer),
       __func__);
  /* Only one read handle is permitted at any time; cancel the existing or wait
     for it to complete */
  GNUNET_assert (NULL == socket->read_handle);
  GNUNET_assert (NULL != proc);
  if (GNUNET_YES == socket->receive_closed)
    return NULL;
  switch (socket->state)
  {
  case STATE_RECEIVE_CLOSED:
  case STATE_RECEIVE_CLOSE_WAIT:
  case STATE_CLOSED:
  case STATE_CLOSE_WAIT:
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s: %s() END\n",
         GNUNET_i2s (&socket->other_peer),
         __func__);
    proc (proc_cls, GNUNET_STREAM_SHUTDOWN, NULL, 0);
    return NULL;
  default:
    break;
  }
  read_handle = GNUNET_malloc (sizeof (struct GNUNET_STREAM_ReadHandle));
  read_handle->proc = proc;
  read_handle->proc_cls = proc_cls;
  read_handle->socket = socket;
  socket->read_handle = read_handle;
  read_handle->probe_data_availability_task_id =
      GNUNET_SCHEDULER_add_now (&probe_data_availability, socket);
  read_handle->read_io_timeout_task_id =
      GNUNET_SCHEDULER_add_delayed (timeout, &read_io_timeout, socket);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "%s: %s() END\n",
       GNUNET_i2s (&socket->other_peer), __func__);
  return read_handle;
}


/**
 * Cancels pending write operation. Also cancels packet retransmissions which
 * may have resulted otherwise.
 *
 * CAUTION: Normally a write operation is considered successful if the data
 * given to it is sent and acknowledged by the receiver. As data is divided
 * into packets, it is possible that not all packets are received by the
 * receiver. Any missing packets are then retransmitted till the receiver
 * acknowledges all packets or until a timeout . During this scenario if the
 * write operation is cancelled all such retransmissions are also
 * cancelled. This may leave the receiver's receive buffer incompletely filled
 * as some missing packets are never retransmitted. So this operation should be
 * used before shutting down transmission from our side or before closing the
 * socket.
 *
 * @param wh write operation handle to cancel
 */
void
GNUNET_STREAM_write_cancel (struct GNUNET_STREAM_WriteHandle *wh)
{
  struct GNUNET_STREAM_Socket *socket = wh->socket;
  unsigned int packet;

  GNUNET_assert (NULL != socket->write_handle);
  GNUNET_assert (socket->write_handle == wh);
  if (GNUNET_SCHEDULER_NO_TASK != socket->data_retransmission_task_id)
  {
    GNUNET_SCHEDULER_cancel (socket->data_retransmission_task_id);
    socket->data_retransmission_task_id = GNUNET_SCHEDULER_NO_TASK;
  }
  for (packet=0; packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH; packet++)
  {
    if (NULL == wh->messages[packet]) break;
    GNUNET_free (wh->messages[packet]);
  }      
  GNUNET_free (socket->write_handle);
  socket->write_handle = NULL;
}


/**
 * Cancel pending read operation.
 *
 * @param rh read operation handle to cancel
 */
void
GNUNET_STREAM_read_cancel (struct GNUNET_STREAM_ReadHandle *rh)
{
  struct GNUNET_STREAM_Socket *socket;
  
  socket = rh->socket;
  GNUNET_assert (NULL != socket->read_handle);
  GNUNET_assert (rh == socket->read_handle);
  cleanup_read_handle (socket);
}


/**
 * Functions of this signature are called whenever writing operations
 * on a stream are executed
 *
 * @param cls the closure from GNUNET_STREAM_write
 * @param status the status of the stream at the time this function is called;
 *          GNUNET_STREAM_OK if writing to stream was completed successfully;
 *          GNUNET_STREAM_TIMEOUT if the given data is not sent successfully
 *          (this doesn't mean that the data is never sent, the receiver may
 *          have read the data but its ACKs may have been lost);
 *          GNUNET_STREAM_SHUTDOWN if the stream is shutdown for writing in the
 *          mean time; GNUNET_STREAM_SYSERR if the stream is broken and cannot
 *          be processed.
 * @param size the number of bytes written
 */
static void 
mq_stream_write_queued (void *cls, enum GNUNET_STREAM_Status status, size_t size)
{
  struct GNUNET_MQ_MessageQueue *mq = cls;
  struct MQStreamState *mss = (struct MQStreamState *) mq->impl_state;
  struct GNUNET_MQ_Message *mqm;

  GNUNET_assert (GNUNET_STREAM_OK == status);
  
  /* call cb for message we finished sending */
  mqm = mq->current_msg;
  GNUNET_assert (NULL != mq->current_msg);
  if (NULL != mqm->sent_cb)
    mqm->sent_cb (mqm->sent_cls);
  GNUNET_free (mqm);

  mss->wh = NULL;

  mqm = mq->msg_head;
  mq->current_msg = mqm;
  if (NULL == mqm)
    return;
  GNUNET_CONTAINER_DLL_remove (mq->msg_head, mq->msg_tail, mqm);
  mss->wh = GNUNET_STREAM_write (mss->socket, mqm->mh, ntohs (mqm->mh->size),
                                 GNUNET_TIME_UNIT_FOREVER_REL,
                                 mq_stream_write_queued, mq);
  GNUNET_assert (NULL != mss->wh);
}


static void
mq_stream_send_impl (struct GNUNET_MQ_MessageQueue *mq,
                     struct GNUNET_MQ_Message *mqm)
{
  struct MQStreamState *mss = (struct MQStreamState *) mq->impl_state;

  if (NULL != mq->current_msg)
  {
    GNUNET_CONTAINER_DLL_insert_tail (mq->msg_head, mq->msg_tail, mqm);
    return;
  }
  mq->current_msg = mqm;
  mss->wh = GNUNET_STREAM_write (mss->socket, mqm->mh, ntohs (mqm->mh->size),
                                 GNUNET_TIME_UNIT_FOREVER_REL,
                                 mq_stream_write_queued, mq);
}


/**
 * Functions with this signature are called whenever a
 * complete message is received by the tokenizer.
 *
 * Do not call GNUNET_SERVER_mst_destroy in callback
 *
 * @param cls closure
 * @param client identification of the client
 * @param message the actual message
 *
 * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
 */
static int
mq_stream_mst_callback (void *cls, void *client,
                     const struct GNUNET_MessageHeader *message)
{
  struct GNUNET_MQ_MessageQueue *mq = cls;

  GNUNET_assert (NULL != message);
  GNUNET_MQ_dispatch (mq, message);
  return GNUNET_OK;
}


/**
 * Functions of this signature are called whenever data is available from the
 * stream.
 *
 * @param cls the closure from GNUNET_STREAM_read
 * @param status the status of the stream at the time this function is called
 * @param data traffic from the other side
 * @param size the number of bytes available in data read; will be 0 on timeout 
 * @return number of bytes of processed from 'data' (any data remaining should be
 *         given to the next time the read processor is called).
 */
static size_t
mq_stream_data_processor (void *cls,
                       enum GNUNET_STREAM_Status status,
                       const void *data,
                       size_t size)
{
  struct GNUNET_MQ_MessageQueue *mq = cls;
  struct MQStreamState *mss;
  int ret;
  
  mss = (struct MQStreamState *) mq->impl_state;
  GNUNET_assert (GNUNET_STREAM_OK == status);
  ret = GNUNET_SERVER_mst_receive (mss->mst, NULL, data, size, GNUNET_NO, GNUNET_NO);
  GNUNET_assert (GNUNET_OK == ret);
  /* we always read all data */
    mss->rh = GNUNET_STREAM_read (mss->socket, GNUNET_TIME_UNIT_FOREVER_REL, 
                                  mq_stream_data_processor, mq);
  return size;
}


static void
mq_stream_destroy_impl (struct GNUNET_MQ_MessageQueue *mq)
{
  struct MQStreamState *mss = (struct MQStreamState *) mq->impl_state;

  if (NULL != mss->rh)
  {
    GNUNET_STREAM_read_cancel (mss->rh);
    mss->rh = NULL;
  }

  if (NULL != mss->wh)
  {
    GNUNET_STREAM_write_cancel (mss->wh);
    mss->wh = NULL;
  }

  if (NULL != mss->mst)
  {
    GNUNET_SERVER_mst_destroy (mss->mst);
    mss->mst = NULL;
  }

  GNUNET_free (mss);
}



/**
 * Create a message queue for a stream socket.
 *
 * @param socket the socket to read/write in the message queue
 * @param msg_handlers message handler array
 * @param error_handler callback for errors
 * @return the message queue for the socket
 */
struct GNUNET_MQ_MessageQueue *
GNUNET_STREAM_mq_create (struct GNUNET_STREAM_Socket *socket, 
                         const struct GNUNET_MQ_Handler *msg_handlers,
                         GNUNET_MQ_ErrorHandler error_handler,
                         void *cls)
{
  struct GNUNET_MQ_MessageQueue *mq;
  struct MQStreamState *mss;

  mq = GNUNET_new (struct GNUNET_MQ_MessageQueue);
  mss = GNUNET_new (struct MQStreamState);
  mss->socket = socket;
  mq->impl_state = mss;
  mq->send_impl = mq_stream_send_impl;
  mq->destroy_impl = mq_stream_destroy_impl;
  mq->handlers = msg_handlers;
  mq->handlers_cls = cls;
  if (NULL != msg_handlers)
  {
    mss->mst = GNUNET_SERVER_mst_create (mq_stream_mst_callback, mq);
    mss->rh = GNUNET_STREAM_read (socket, GNUNET_TIME_UNIT_FOREVER_REL, 
                                  mq_stream_data_processor, mq);
  }
  return mq;
}

/* end of stream_api.c */