summaryrefslogtreecommitdiffstats
path: root/src/channels.c
blob: 7a4e71fed5ccf606a57b54f0bc82878954b2f79a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
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
/*
 * channels.c - SSH channel functions
 *
 * This file is part of the SSH Library
 *
 * Copyright (c) 2003-2013 by Aris Adamantiadis
 * Copyright (c) 2009-2013 by Andreas Schneider <asn@cryptomilk.org>
 *
 * The SSH Library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at your
 * option) any later version.
 *
 * The SSH Library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the SSH Library; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
 * MA 02111-1307, USA.
 */

#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>

#ifndef _WIN32
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#include "libssh/priv.h"
#include "libssh/ssh2.h"
#include "libssh/buffer.h"
#include "libssh/packet.h"
#include "libssh/socket.h"
#include "libssh/channels.h"
#include "libssh/session.h"
#include "libssh/misc.h"
#include "libssh/messages.h"
#if WITH_SERVER
#include "libssh/server.h"
#endif

#define WINDOWBASE 1280000
#define WINDOWLIMIT (WINDOWBASE/2)

/*
 * All implementations MUST be able to process packets with an
 * uncompressed payload length of 32768 bytes or less and a total packet
 * size of 35000 bytes or less.
 */
#define CHANNEL_MAX_PACKET 32768
#define CHANNEL_INITIAL_WINDOW 64000

/**
 * @defgroup libssh_channel The SSH channel functions
 * @ingroup libssh
 *
 * Functions that manage a SSH channel.
 *
 * @{
 */

static ssh_channel channel_from_msg(ssh_session session, ssh_buffer packet);

/**
 * @brief Allocate a new channel.
 *
 * @param[in]  session  The ssh session to use.
 *
 * @return              A pointer to a newly allocated channel, NULL on error.
 */
ssh_channel ssh_channel_new(ssh_session session) {
  ssh_channel channel = NULL;

  if(session == NULL) {
      return NULL;
  }

  channel = malloc(sizeof(struct ssh_channel_struct));
  if (channel == NULL) {
    ssh_set_error_oom(session);
    return NULL;
  }
  memset(channel,0,sizeof(struct ssh_channel_struct));

  channel->stdout_buffer = ssh_buffer_new();
  if (channel->stdout_buffer == NULL) {
    ssh_set_error_oom(session);
    SAFE_FREE(channel);
    return NULL;
  }

  channel->stderr_buffer = ssh_buffer_new();
  if (channel->stderr_buffer == NULL) {
    ssh_set_error_oom(session);
    ssh_buffer_free(channel->stdout_buffer);
    SAFE_FREE(channel);
    return NULL;
  }

  channel->session = session;
  channel->version = session->version;
  channel->exit_status = -1;
  channel->flags = SSH_CHANNEL_FLAG_NOT_BOUND;

  if(session->channels == NULL) {
    session->channels = ssh_list_new();
  }
  ssh_list_prepend(session->channels, channel);
  return channel;
}

/**
 * @internal
 *
 * @brief Create a new channel identifier.
 *
 * @param[in]  session  The SSH session to use.
 *
 * @return              The new channel identifier.
 */
uint32_t ssh_channel_new_id(ssh_session session) {
  return ++(session->maxchannel);
}

/**
 * @internal
 *
 * @brief Handle a SSH_PACKET_CHANNEL_OPEN_CONFIRMATION packet.
 *
 * Constructs the channel object.
 */
SSH_PACKET_CALLBACK(ssh_packet_channel_open_conf){
  uint32_t channelid=0;
  ssh_channel channel;
  int rc;
  (void)type;
  (void)user;

  SSH_LOG(SSH_LOG_PACKET,"Received SSH2_MSG_CHANNEL_OPEN_CONFIRMATION");

  rc = ssh_buffer_unpack(packet, "d", &channelid);
  if (rc != SSH_OK)
      goto error;
  channel=ssh_channel_from_local(session,channelid);
  if(channel==NULL){
    ssh_set_error(session, SSH_FATAL,
        "Unknown channel id %lu",
        (long unsigned int) channelid);
    /* TODO: Set error marking in channel object */

    return SSH_PACKET_USED;
  }

  rc = ssh_buffer_unpack(packet, "ddd",
          &channel->remote_channel,
          &channel->remote_window,
          &channel->remote_maxpacket);
  if (rc != SSH_OK)
      goto error;

  SSH_LOG(SSH_LOG_PROTOCOL,
      "Received a CHANNEL_OPEN_CONFIRMATION for channel %d:%d",
      channel->local_channel,
      channel->remote_channel);
  SSH_LOG(SSH_LOG_PROTOCOL,
      "Remote window : %lu, maxpacket : %lu",
      (long unsigned int) channel->remote_window,
      (long unsigned int) channel->remote_maxpacket);

  channel->state = SSH_CHANNEL_STATE_OPEN;
  channel->flags &= ~SSH_CHANNEL_FLAG_NOT_BOUND;
  return SSH_PACKET_USED;

error:
  ssh_set_error(session, SSH_FATAL, "Invalid packet");
  return SSH_PACKET_USED;
}

/**
 * @internal
 *
 * @brief Handle a SSH_CHANNEL_OPEN_FAILURE and set the state of the channel.
 */
SSH_PACKET_CALLBACK(ssh_packet_channel_open_fail){

  ssh_channel channel;
  char *error = NULL;
  uint32_t code;
  int rc;
  (void)user;
  (void)type;

  channel=channel_from_msg(session,packet);
  if(channel==NULL){
    SSH_LOG(SSH_LOG_RARE,"Invalid channel in packet");
    return SSH_PACKET_USED;
  }

  rc = ssh_buffer_unpack(packet, "ds", &code, &error);
  if (rc != SSH_OK){
      ssh_set_error(session, SSH_FATAL, "Invalid packet");
      return SSH_PACKET_USED;
  }

  ssh_set_error(session, SSH_REQUEST_DENIED,
      "Channel opening failure: channel %u error (%lu) %s",
      channel->local_channel,
      (long unsigned int) code,
      error);
  SAFE_FREE(error);
  channel->state=SSH_CHANNEL_STATE_OPEN_DENIED;
  return SSH_PACKET_USED;
}

static int ssh_channel_open_termination(void *c){
  ssh_channel channel = (ssh_channel) c;
  if (channel->state != SSH_CHANNEL_STATE_OPENING ||
      channel->session->session_state == SSH_SESSION_STATE_ERROR)
    return 1;
  else
    return 0;
}

/**
 * @internal
 *
 * @brief Open a channel by sending a SSH_OPEN_CHANNEL message and
 *        wait for the reply.
 *
 * @param[in]  channel  The current channel.
 *
 * @param[in]  type   A C string describing the kind of channel (e.g. "exec").
 *
 * @param[in]  window   The receiving window of the channel. The window is the
 *                      maximum size of data that can stay in buffers and
 *                      network.
 *
 * @param[in]  maxpacket The maximum packet size allowed (like MTU).
 *
 * @param[in]  payload   The buffer containing additional payload for the query.
 */
static int channel_open(ssh_channel channel, const char *type, int window,
    int maxpacket, ssh_buffer payload) {
  ssh_session session = channel->session;
  int err=SSH_ERROR;
  int rc;

  switch(channel->state){
  case SSH_CHANNEL_STATE_NOT_OPEN:
    break;
  case SSH_CHANNEL_STATE_OPENING:
    goto pending;
  case SSH_CHANNEL_STATE_OPEN:
  case SSH_CHANNEL_STATE_CLOSED:
  case SSH_CHANNEL_STATE_OPEN_DENIED:
    goto end;
  default:
    ssh_set_error(session,SSH_FATAL,"Bad state in channel_open: %d",channel->state);
  }
  channel->local_channel = ssh_channel_new_id(session);
  channel->local_maxpacket = maxpacket;
  channel->local_window = window;

  SSH_LOG(SSH_LOG_PROTOCOL,
      "Creating a channel %d with %d window and %d max packet",
      channel->local_channel, window, maxpacket);

  rc = ssh_buffer_pack(session->out_buffer,
                       "bsddd",
                       SSH2_MSG_CHANNEL_OPEN,
                       type,
                       channel->local_channel,
                       channel->local_window,
                       channel->local_maxpacket);
  if (rc != SSH_OK){
    ssh_set_error_oom(session);
    return err;
  }

  if (payload != NULL) {
    if (buffer_add_buffer(session->out_buffer, payload) < 0) {
      ssh_set_error_oom(session);

      return err;
    }
  }
  channel->state = SSH_CHANNEL_STATE_OPENING;
  if (packet_send(session) == SSH_ERROR) {

    return err;
  }

  SSH_LOG(SSH_LOG_PACKET,
      "Sent a SSH_MSG_CHANNEL_OPEN type %s for channel %d",
      type, channel->local_channel);
pending:
  /* wait until channel is opened by server */
  err = ssh_handle_packets_termination(session,
                                       SSH_TIMEOUT_DEFAULT,
                                       ssh_channel_open_termination,
                                       channel);

  if (session->session_state == SSH_SESSION_STATE_ERROR)
    err = SSH_ERROR;
end:
  if(channel->state == SSH_CHANNEL_STATE_OPEN)
    err=SSH_OK;

  return err;
}

/* return channel with corresponding local id, or NULL if not found */
ssh_channel ssh_channel_from_local(ssh_session session, uint32_t id) {
  struct ssh_iterator *it;
  ssh_channel channel;

  for (it = ssh_list_get_iterator(session->channels); it != NULL ; it=it->next) {
    channel = ssh_iterator_value(ssh_channel, it);
    if (channel == NULL) {
      continue;
    }
    if (channel->local_channel == id) {
      return channel;
    }
  }

  return NULL;
}

/**
 * @internal
 * @brief grows the local window and send a packet to the other party
 * @param session SSH session
 * @param channel SSH channel
 * @param minimumsize The minimum acceptable size for the new window.
 */
static int grow_window(ssh_session session, ssh_channel channel, int minimumsize) {
  uint32_t new_window = minimumsize > WINDOWBASE ? minimumsize : WINDOWBASE;
  int rc;

#ifdef WITH_SSH1
  if (session->version == 1){
      channel->remote_window = new_window;

      return SSH_OK;
  }
#endif
  if(new_window <= channel->local_window){
    SSH_LOG(SSH_LOG_PROTOCOL,
        "growing window (channel %d:%d) to %d bytes : not needed (%d bytes)",
        channel->local_channel, channel->remote_channel, new_window,
        channel->local_window);

    return SSH_OK;
  }
  /* WINDOW_ADJUST packet needs a relative increment rather than an absolute
   * value, so we give here the missing bytes needed to reach new_window
   */
  rc = ssh_buffer_pack(session->out_buffer,
                       "bdd",
                       SSH2_MSG_CHANNEL_WINDOW_ADJUST,
                       channel->remote_channel,
                       new_window - channel->local_window);
  if (rc != SSH_OK) {
    ssh_set_error_oom(session);
    goto error;
  }

  if (packet_send(session) == SSH_ERROR) {
    goto error;
  }

  SSH_LOG(SSH_LOG_PROTOCOL,
      "growing window (channel %d:%d) to %d bytes",
      channel->local_channel,
      channel->remote_channel,
      new_window);

  channel->local_window = new_window;

  return SSH_OK;
error:
  ssh_buffer_reinit(session->out_buffer);

  return SSH_ERROR;
}

/**
 * @internal
 *
 * @brief Parse a channel-related packet to resolve it to a ssh_channel.
 *
 * This works on SSH1 sessions too.
 *
 * @param[in]  session  The current SSH session.
 *
 * @param[in]  packet   The buffer to parse packet from. The read pointer will
 *                      be moved after the call.
 *
 * @returns             The related ssh_channel, or NULL if the channel is
 *                      unknown or the packet is invalid.
 */
static ssh_channel channel_from_msg(ssh_session session, ssh_buffer packet) {
  ssh_channel channel;
  uint32_t chan;
  int rc;
#ifdef WITH_SSH1
  /* With SSH1, the channel is always the first one */
  if(session->version==1)
    return ssh_get_channel1(session);
#endif
  rc = ssh_buffer_unpack(packet,"d",&chan);
  if (rc != SSH_OK) {
    ssh_set_error(session, SSH_FATAL,
        "Getting channel from message: short read");
    return NULL;
  }

  channel = ssh_channel_from_local(session, chan);
  if (channel == NULL) {
    ssh_set_error(session, SSH_FATAL,
        "Server specified invalid channel %lu",
        (long unsigned int) chan);
  }

  return channel;
}

SSH_PACKET_CALLBACK(channel_rcv_change_window) {
  ssh_channel channel;
  uint32_t bytes;
  int rc;
  (void)user;
  (void)type;

  channel = channel_from_msg(session,packet);
  if (channel == NULL) {
    SSH_LOG(SSH_LOG_FUNCTIONS, "%s", ssh_get_error(session));
  }

  rc = ssh_buffer_unpack(packet, "d", &bytes);
  if (channel == NULL || rc != SSH_OK) {
    SSH_LOG(SSH_LOG_PACKET,
        "Error getting a window adjust message: invalid packet");

    return SSH_PACKET_USED;
  }

  SSH_LOG(SSH_LOG_PROTOCOL,
      "Adding %d bytes to channel (%d:%d) (from %d bytes)",
      bytes,
      channel->local_channel,
      channel->remote_channel,
      channel->remote_window);

  channel->remote_window += bytes;

  return SSH_PACKET_USED;
}

/* is_stderr is set to 1 if the data are extended, ie stderr */
SSH_PACKET_CALLBACK(channel_rcv_data){
  ssh_channel channel;
  ssh_string str;
  ssh_buffer buf;
  size_t len;
  int is_stderr;
  int rest;
  (void)user;

  if(type==SSH2_MSG_CHANNEL_DATA)
	  is_stderr=0;
  else
	  is_stderr=1;

  channel = channel_from_msg(session,packet);
  if (channel == NULL) {
    SSH_LOG(SSH_LOG_FUNCTIONS,
        "%s", ssh_get_error(session));

    return SSH_PACKET_USED;
  }

  if (is_stderr) {
    uint32_t ignore;
    /* uint32 data type code. we can ignore it */
    buffer_get_u32(packet, &ignore);
  }

  str = buffer_get_ssh_string(packet);
  if (str == NULL) {
    SSH_LOG(SSH_LOG_PACKET, "Invalid data packet!");

    return SSH_PACKET_USED;
  }
  len = ssh_string_len(str);

  SSH_LOG(SSH_LOG_PACKET,
      "Channel receiving %" PRIdS " bytes data in %d (local win=%d remote win=%d)",
      len,
      is_stderr,
      channel->local_window,
      channel->remote_window);

  /* What shall we do in this case? Let's accept it anyway */
  if (len > channel->local_window) {
    SSH_LOG(SSH_LOG_RARE,
        "Data packet too big for our window(%" PRIdS " vs %d)",
        len,
        channel->local_window);
  }

  if (channel_default_bufferize(channel, ssh_string_data(str), len,
        is_stderr) < 0) {
    ssh_string_free(str);

    return SSH_PACKET_USED;
  }

  if (len <= channel->local_window) {
    channel->local_window -= len;
  } else {
    channel->local_window = 0; /* buggy remote */
  }

  SSH_LOG(SSH_LOG_PACKET,
      "Channel windows are now (local win=%d remote win=%d)",
      channel->local_window,
      channel->remote_window);

  ssh_string_free(str);

  if(ssh_callbacks_exists(channel->callbacks, channel_data_function)) {
      if(is_stderr) {
        buf = channel->stderr_buffer;
      } else {
        buf = channel->stdout_buffer;
      }
      rest = channel->callbacks->channel_data_function(channel->session,
                                                channel,
                                                buffer_get_rest(buf),
                                                buffer_get_rest_len(buf),
                                                is_stderr,
                                                channel->callbacks->userdata);
      if(rest > 0) {
        if (channel->counter != NULL) {
            channel->counter->in_bytes += rest;
        }
        buffer_pass_bytes(buf, rest);
      }
      if (channel->local_window + buffer_get_rest_len(buf) < WINDOWLIMIT) {
        if (grow_window(session, channel, 0) < 0) {
          return -1;
        }
      }
  }

  return SSH_PACKET_USED;
}

SSH_PACKET_CALLBACK(channel_rcv_eof) {
  ssh_channel channel;
  (void)user;
  (void)type;

  channel = channel_from_msg(session,packet);
  if (channel == NULL) {
    SSH_LOG(SSH_LOG_FUNCTIONS, "%s", ssh_get_error(session));

    return SSH_PACKET_USED;
  }

  SSH_LOG(SSH_LOG_PACKET,
      "Received eof on channel (%d:%d)",
      channel->local_channel,
      channel->remote_channel);
  /* channel->remote_window = 0; */
  channel->remote_eof = 1;

  if(ssh_callbacks_exists(channel->callbacks, channel_eof_function)) {
      channel->callbacks->channel_eof_function(channel->session,
                                               channel,
                                               channel->callbacks->userdata);
  }

  return SSH_PACKET_USED;
}

SSH_PACKET_CALLBACK(channel_rcv_close) {
	ssh_channel channel;
	(void)user;
	(void)type;

	channel = channel_from_msg(session,packet);
	if (channel == NULL) {
		SSH_LOG(SSH_LOG_FUNCTIONS, "%s", ssh_get_error(session));

		return SSH_PACKET_USED;
	}

	SSH_LOG(SSH_LOG_PACKET,
			"Received close on channel (%d:%d)",
			channel->local_channel,
			channel->remote_channel);

	if ((channel->stdout_buffer &&
			buffer_get_rest_len(channel->stdout_buffer) > 0) ||
			(channel->stderr_buffer &&
					buffer_get_rest_len(channel->stderr_buffer) > 0)) {
		channel->delayed_close = 1;
	} else {
		channel->state = SSH_CHANNEL_STATE_CLOSED;
	}
	if (channel->remote_eof == 0) {
		SSH_LOG(SSH_LOG_PACKET,
				"Remote host not polite enough to send an eof before close");
	}
	channel->remote_eof = 1;
	/*
	 * The remote eof doesn't break things if there was still data into read
	 * buffer because the eof is ignored until the buffer is empty.
	 */

	if(ssh_callbacks_exists(channel->callbacks, channel_close_function)) {
	  channel->callbacks->channel_close_function(channel->session,
	      channel,
	      channel->callbacks->userdata);
	}
	channel->flags |= SSH_CHANNEL_FLAG_CLOSED_REMOTE;
	if(channel->flags & SSH_CHANNEL_FLAG_FREED_LOCAL)
	  ssh_channel_do_free(channel);

	return SSH_PACKET_USED;
}

SSH_PACKET_CALLBACK(channel_rcv_request) {
	ssh_channel channel;
	char *request=NULL;
    uint8_t status;
    int rc;
	(void)user;
	(void)type;

	channel = channel_from_msg(session,packet);
	if (channel == NULL) {
		SSH_LOG(SSH_LOG_FUNCTIONS,"%s", ssh_get_error(session));
		return SSH_PACKET_USED;
	}

	rc = ssh_buffer_unpack(packet, "sb",
	        &request,
	        &status);
	if (rc != SSH_OK) {
		SSH_LOG(SSH_LOG_PACKET, "Invalid MSG_CHANNEL_REQUEST");
		return SSH_PACKET_USED;
	}

	if (strcmp(request,"exit-status") == 0) {
        uint32_t exit_status = 0;

		SAFE_FREE(request);
        rc = ssh_buffer_unpack(packet, "d", &exit_status);
		SSH_LOG(SSH_LOG_PACKET, "received exit-status %d", channel->exit_status);

        if(ssh_callbacks_exists(channel->callbacks, channel_exit_status_function)) {
            channel->callbacks->channel_exit_status_function(channel->session,
                                                     channel,
                                                     channel->exit_status,
                                                     channel->callbacks->userdata);
        }

		return SSH_PACKET_USED;
	}

	if (strcmp(request,"signal") == 0) {
        char *sig = NULL;

		SAFE_FREE(request);
		SSH_LOG(SSH_LOG_PACKET, "received signal");

		rc = ssh_buffer_unpack(packet, "s", &sig);
		if (rc != SSH_OK) {
			SSH_LOG(SSH_LOG_PACKET, "Invalid MSG_CHANNEL_REQUEST");
			return SSH_PACKET_USED;
		}

		SSH_LOG(SSH_LOG_PACKET,
				"Remote connection sent a signal SIG %s", sig);
        if(ssh_callbacks_exists(channel->callbacks, channel_signal_function)) {
            channel->callbacks->channel_signal_function(channel->session,
                                                     channel,
                                                     sig,
                                                     channel->callbacks->userdata);
        }
        SAFE_FREE(sig);

		return SSH_PACKET_USED;
	}

	if (strcmp(request, "exit-signal") == 0) {
		const char *core = "(core dumped)";
		char *sig = NULL;
		char *errmsg = NULL;
		char *lang = NULL;
		uint8_t core_dumped;

		SAFE_FREE(request);

		rc = ssh_buffer_unpack(packet, "sbs",
		        &sig, /* signal name */
		        &core_dumped,    /* core dumped */
		        &errmsg, /* error message */
		        &lang);
		if (rc != SSH_OK) {
			SSH_LOG(SSH_LOG_PACKET, "Invalid MSG_CHANNEL_REQUEST");
			return SSH_PACKET_USED;
		}

		if (core_dumped == 0) {
			core = "";
		}

		SSH_LOG(SSH_LOG_PACKET,
				"Remote connection closed by signal SIG %s %s", sig, core);
        if(ssh_callbacks_exists(channel->callbacks, channel_exit_signal_function)) {
            channel->callbacks->channel_exit_signal_function(channel->session,
                                                     channel,
                                                     sig, core_dumped, errmsg, lang,
                                                     channel->callbacks->userdata);
        }

        SAFE_FREE(lang);
        SAFE_FREE(errmsg);
		SAFE_FREE(sig);

		return SSH_PACKET_USED;
	}
	if(strcmp(request,"keepalive@openssh.com")==0){
	  SAFE_FREE(request);
	  SSH_LOG(SSH_LOG_PROTOCOL,"Responding to Openssh's keepalive");

      rc = ssh_buffer_pack(session->out_buffer,
                           "bd",
                           SSH2_MSG_CHANNEL_FAILURE,
                           channel->remote_channel);
      if (rc != SSH_OK) {
          return SSH_PACKET_USED;
      }
	  packet_send(session);

	  return SSH_PACKET_USED;
	}

  if (strcmp(request, "auth-agent-req@openssh.com") == 0) {
    SAFE_FREE(request);
    SSH_LOG(SSH_LOG_PROTOCOL, "Received an auth-agent-req request");
    if(ssh_callbacks_exists(channel->callbacks, channel_auth_agent_req_function)) {
        channel->callbacks->channel_auth_agent_req_function(channel->session, channel,
            channel->callbacks->userdata);
    }

    return SSH_PACKET_USED;
  }
#ifdef WITH_SERVER
	/* If we are here, that means we have a request that is not in the understood
	 * client requests. That means we need to create a ssh message to be passed
	 * to the user code handling ssh messages
	 */
	ssh_message_handle_channel_request(session,channel,packet,request,status);
#else
    SSH_LOG(SSH_LOG_WARNING, "Unhandled channel request %s", request);
#endif
	
	SAFE_FREE(request);

	return SSH_PACKET_USED;
}

/*
 * When data has been received from the ssh server, it can be applied to the
 * known user function, with help of the callback, or inserted here
 *
 * FIXME is the window changed?
 */
int channel_default_bufferize(ssh_channel channel, void *data, int len,
    int is_stderr) {
  ssh_session session;

  if(channel == NULL) {
      return -1;
  }

  session = channel->session;

  if(data == NULL) {
      ssh_set_error_invalid(session);
      return -1;
  }

  SSH_LOG(SSH_LOG_PACKET,
      "placing %d bytes into channel buffer (stderr=%d)", len, is_stderr);
  if (is_stderr == 0) {
    /* stdout */
    if (channel->stdout_buffer == NULL) {
      channel->stdout_buffer = ssh_buffer_new();
      if (channel->stdout_buffer == NULL) {
        ssh_set_error_oom(session);
        return -1;
      }
    }

    if (ssh_buffer_add_data(channel->stdout_buffer, data, len) < 0) {
      ssh_set_error_oom(session);
      ssh_buffer_free(channel->stdout_buffer);
      channel->stdout_buffer = NULL;
      return -1;
    }
  } else {
    /* stderr */
    if (channel->stderr_buffer == NULL) {
      channel->stderr_buffer = ssh_buffer_new();
      if (channel->stderr_buffer == NULL) {
        ssh_set_error_oom(session);
        return -1;
      }
    }

    if (ssh_buffer_add_data(channel->stderr_buffer, data, len) < 0) {
      ssh_set_error_oom(session);
      ssh_buffer_free(channel->stderr_buffer);
      channel->stderr_buffer = NULL;
      return -1;
    }
  }

  return 0;
}

/**
 * @brief Open a session channel (suited for a shell, not TCP forwarding).
 *
 * @param[in]  channel  An allocated channel.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 *
 * @see ssh_channel_open_forward()
 * @see ssh_channel_request_env()
 * @see ssh_channel_request_shell()
 * @see ssh_channel_request_exec()
 */
int ssh_channel_open_session(ssh_channel channel) {
  if(channel == NULL) {
      return SSH_ERROR;
  }

#ifdef WITH_SSH1
  if (channel->session->version == 1) {
    return channel_open_session1(channel);
  }
#endif

  return channel_open(channel,
                      "session",
                      CHANNEL_INITIAL_WINDOW,
                      CHANNEL_MAX_PACKET,
                      NULL);
}

/**
 * @brief Open an agent authentication forwarding channel. This type of channel
 * can be opened by a server towards a client in order to provide SSH-Agent services
 * to the server-side process. This channel can only be opened if the client
 * claimed support by sending a channel request beforehand.
 *
 * @param[in]  channel  An allocated channel.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 *
 * @see ssh_channel_open_forward()
 */
int ssh_channel_open_auth_agent(ssh_channel channel){
  if(channel == NULL) {
      return SSH_ERROR;
  }

#ifdef WITH_SSH1
  if (channel->session->version == 1) {
    return SSH_ERROR;
  }
#endif

  return channel_open(channel,
                      "auth-agent@openssh.com",
                      CHANNEL_INITIAL_WINDOW,
                      CHANNEL_MAX_PACKET,
                      NULL);
}


/**
 * @brief Open a TCP/IP forwarding channel.
 *
 * @param[in]  channel  An allocated channel.
 *
 * @param[in]  remotehost The remote host to connected (host name or IP).
 *
 * @param[in]  remoteport The remote port.
 *
 * @param[in]  sourcehost The numeric IP address of the machine from where the
 *                        connection request originates. This is mostly for
 *                        logging purposes.
 *
 * @param[in]  localport  The port on the host from where the connection
 *                        originated. This is mostly for logging purposes.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 *
 * @warning This function does not bind the local port and does not automatically
 *          forward the content of a socket to the channel. You still have to
 *          use channel_read and channel_write for this.
 */
int ssh_channel_open_forward(ssh_channel channel, const char *remotehost,
    int remoteport, const char *sourcehost, int localport) {
  ssh_session session;
  ssh_buffer payload = NULL;
  ssh_string str = NULL;
  int rc = SSH_ERROR;

  if(channel == NULL) {
      return rc;
  }

  session = channel->session;

  if(remotehost == NULL || sourcehost == NULL) {
      ssh_set_error_invalid(session);
      return rc;
  }

  payload = ssh_buffer_new();
  if (payload == NULL) {
    ssh_set_error_oom(session);
    goto error;
  }

  rc = ssh_buffer_pack(payload,
                       "sdsd",
                       remotehost,
                       remoteport,
                       sourcehost,
                       localport);
  if (rc != SSH_OK) {
    ssh_set_error_oom(session);
    goto error;
  }

  rc = channel_open(channel,
                    "direct-tcpip",
                    CHANNEL_INITIAL_WINDOW,
                    CHANNEL_MAX_PACKET,
                    payload);

error:
  ssh_buffer_free(payload);
  ssh_string_free(str);

  return rc;
}


/**
 * @brief Close and free a channel.
 *
 * @param[in]  channel  The channel to free.
 *
 * @warning Any data unread on this channel will be lost.
 */
void ssh_channel_free(ssh_channel channel) {
  ssh_session session;

  if (channel == NULL) {
    return;
  }

  session = channel->session;
  if (session->alive && channel->state == SSH_CHANNEL_STATE_OPEN) {
    ssh_channel_close(channel);
  }
  channel->flags |= SSH_CHANNEL_FLAG_FREED_LOCAL;

  /* The idea behind the flags is the following : it is well possible
   * that a client closes a channel that stills exists on the server side.
   * We definitively close the channel when we receive a close message *and*
   * the user closed it.
   */
  if((channel->flags & SSH_CHANNEL_FLAG_CLOSED_REMOTE)
      || (channel->flags & SSH_CHANNEL_FLAG_NOT_BOUND)){
    ssh_channel_do_free(channel);
  }
}

/**
 * @internal
 * @brief Effectively free a channel, without caring about flags
 */

void ssh_channel_do_free(ssh_channel channel){
  struct ssh_iterator *it;
  ssh_session session = channel->session;
  it = ssh_list_find(session->channels, channel);
  if(it != NULL){
    ssh_list_remove(session->channels, it);
  }
  ssh_buffer_free(channel->stdout_buffer);
  ssh_buffer_free(channel->stderr_buffer);

  /* debug trick to catch use after frees */
  memset(channel, 'X', sizeof(struct ssh_channel_struct));
  SAFE_FREE(channel);
}

/**
 * @brief Send an end of file on the channel.
 *
 * This doesn't close the channel. You may still read from it but not write.
 *
 * @param[in]  channel  The channel to send the eof to.
 *
 * @return              SSH_OK on success, SSH_ERROR if an error occurred.
 *
 * Example:
@code
   rc = ssh_channel_send_eof(channel);
   if (rc == SSH_ERROR) {
       return -1;
   }
   while(!ssh_channel_is_eof(channel)) {
       rc = ssh_channel_read(channel, buf, sizeof(buf), 0);
       if (rc == SSH_ERROR) {
           return -1;
       }
   }
   ssh_channel_close(channel);
@endcode
 *
 * @see ssh_channel_close()
 * @see ssh_channel_free()
 * @see ssh_channel_is_eof()
 */
int ssh_channel_send_eof(ssh_channel channel){
  ssh_session session;
  int rc = SSH_ERROR;
  int err;

  if(channel == NULL) {
      return rc;
  }

  session = channel->session;

  err = ssh_buffer_pack(session->out_buffer,
                        "bd",
                        SSH2_MSG_CHANNEL_EOF,
                        channel->remote_channel);
  if (err != SSH_OK) {
    ssh_set_error_oom(session);
    goto error;
  }

  rc = packet_send(session);
  SSH_LOG(SSH_LOG_PACKET,
      "Sent a EOF on client channel (%d:%d)",
      channel->local_channel,
      channel->remote_channel);

  rc = ssh_channel_flush(channel);
  if(rc == SSH_ERROR)
    goto error;

  channel->local_eof = 1;

  return rc;
error:
  ssh_buffer_reinit(session->out_buffer);

  return rc;
}

/**
 * @brief Close a channel.
 *
 * This sends an end of file and then closes the channel. You won't be able
 * to recover any data the server was going to send or was in buffers.
 *
 * @param[in]  channel  The channel to close.
 *
 * @return              SSH_OK on success, SSH_ERROR if an error occurred.
 *
 * @see ssh_channel_free()
 * @see ssh_channel_is_eof()
 */
int ssh_channel_close(ssh_channel channel){
  ssh_session session;
  int rc = 0;

  if(channel == NULL) {
    return SSH_ERROR;
  }

  session = channel->session;

  if (channel->local_eof == 0) {
    rc = ssh_channel_send_eof(channel);
  }

  if (rc != SSH_OK) {
    return rc;
  }

  rc = ssh_buffer_pack(session->out_buffer,
                       "bd",
                       SSH2_MSG_CHANNEL_CLOSE,
                       channel->remote_channel);
  if (rc != SSH_OK) {
    ssh_set_error_oom(session);
    goto error;
  }

  rc = packet_send(session);
  SSH_LOG(SSH_LOG_PACKET,
      "Sent a close on client channel (%d:%d)",
      channel->local_channel,
      channel->remote_channel);

  if(rc == SSH_OK) {
    channel->state=SSH_CHANNEL_STATE_CLOSED;
  }

  rc = ssh_channel_flush(channel);
  if(rc == SSH_ERROR)
    goto error;

  return rc;
error:
  ssh_buffer_reinit(session->out_buffer);

  return rc;
}

/* this termination function waits for a window growing condition */
static int ssh_channel_waitwindow_termination(void *c){
  ssh_channel channel = (ssh_channel) c;
  if (channel->remote_window > 0 ||
      channel->session->session_state == SSH_SESSION_STATE_ERROR ||
      channel->state == SSH_CHANNEL_STATE_CLOSED)
    return 1;
  else
    return 0;
}

/* This termination function waits until the session is not in blocked status
 * anymore, e.g. because of a key re-exchange.
 */
static int ssh_waitsession_unblocked(void *s){
    ssh_session session = (ssh_session)s;
    switch (session->session_state){
        case SSH_SESSION_STATE_DH:
        case SSH_SESSION_STATE_INITIAL_KEX:
        case SSH_SESSION_STATE_KEXINIT_RECEIVED:
            return 0;
        default:
            return 1;
    }
}
/**
 * @internal
 * @brief Flushes a channel (and its session) until the output buffer
 *        is empty, or timeout elapsed.
 * @param channel SSH channel
 * @returns SSH_OK On success,
 *          SSH_ERROR on error
 *          SSH_AGAIN Timeout elapsed (or in nonblocking mode)
 */
int ssh_channel_flush(ssh_channel channel){
  return ssh_blocking_flush(channel->session, SSH_TIMEOUT_DEFAULT);
}

static int channel_write_common(ssh_channel channel,
                                const void *data,
                                uint32_t len, int is_stderr)
{
  ssh_session session;
  uint32_t origlen = len;
  size_t effectivelen;
  size_t maxpacketlen;
  int rc;

  if(channel == NULL) {
      return -1;
  }
  session = channel->session;
  if(data == NULL) {
      ssh_set_error_invalid(session);
      return -1;
  }

  if (len > INT_MAX) {
      SSH_LOG(SSH_LOG_PROTOCOL,
              "Length (%u) is bigger than INT_MAX", len);
      return SSH_ERROR;
  }

  /*
   * Handle the max packet len from remote side, be nice
   * 10 bytes for the headers
   */
  maxpacketlen = channel->remote_maxpacket - 10;

  if (channel->local_eof) {
    ssh_set_error(session, SSH_REQUEST_DENIED,
        "Can't write to channel %d:%d  after EOF was sent",
        channel->local_channel,
        channel->remote_channel);
    return -1;
  }

  if (channel->state != SSH_CHANNEL_STATE_OPEN || channel->delayed_close != 0) {
    ssh_set_error(session, SSH_REQUEST_DENIED, "Remote channel is closed");

    return -1;
  }

  if (channel->session->session_state == SSH_SESSION_STATE_ERROR) {
    return SSH_ERROR;
  }
#ifdef WITH_SSH1
  if (channel->version == 1) {
    rc = channel_write1(channel, data, len);

    return rc;
  }
#endif
  if (ssh_waitsession_unblocked(session) == 0){
    rc = ssh_handle_packets_termination(session, SSH_TIMEOUT_DEFAULT,
            ssh_waitsession_unblocked, session);
    if (rc == SSH_ERROR || !ssh_waitsession_unblocked(session))
        goto out;
  }
  while (len > 0) {
    if (channel->remote_window < len) {
      SSH_LOG(SSH_LOG_PROTOCOL,
          "Remote window is %d bytes. going to write %d bytes",
          channel->remote_window,
          len);
      /* What happens when the channel window is zero? */
      if(channel->remote_window == 0) {
          /* nothing can be written */
          SSH_LOG(SSH_LOG_PROTOCOL,
                "Wait for a growing window message...");
          rc = ssh_handle_packets_termination(session, SSH_TIMEOUT_DEFAULT,
              ssh_channel_waitwindow_termination,channel);
          if (rc == SSH_ERROR ||
              !ssh_channel_waitwindow_termination(channel) ||
              channel->session->session_state == SSH_SESSION_STATE_ERROR ||
              channel->state == SSH_CHANNEL_STATE_CLOSED)
            goto out;
          continue;
      }
      effectivelen = MIN(len, channel->remote_window);
    } else {
      effectivelen = len;
    }

    effectivelen = MIN(effectivelen, maxpacketlen);;

    rc = ssh_buffer_pack(session->out_buffer,
                         "bd",
                         is_stderr ? SSH2_MSG_CHANNEL_EXTENDED_DATA : SSH2_MSG_CHANNEL_DATA,
                         channel->remote_channel);
    if (rc != SSH_OK) {
        ssh_set_error_oom(session);
        goto error;
    }

    /* stderr message has an extra field */
    if (is_stderr) {
        rc = ssh_buffer_pack(session->out_buffer,
                             "d",
                             SSH2_EXTENDED_DATA_STDERR);
        if (rc != SSH_OK) {
            ssh_set_error_oom(session);
            goto error;
        }
    }

    /* append payload data */
    rc = ssh_buffer_pack(session->out_buffer,
                         "dP",
                         effectivelen,
                         (size_t)effectivelen, data);
    if (rc != SSH_OK) {
        ssh_set_error_oom(session);
        goto error;
    }

    rc = packet_send(session);
    if (rc == SSH_ERROR) {
        return SSH_ERROR;
    }

    SSH_LOG(SSH_LOG_PACKET,
        "channel_write wrote %ld bytes", (long int) effectivelen);

    channel->remote_window -= effectivelen;
    len -= effectivelen;
    data = ((uint8_t*)data + effectivelen);
    if (channel->counter != NULL) {
        channel->counter->out_bytes += effectivelen;
    }
  }

  /* it's a good idea to flush the socket now */
  rc = ssh_channel_flush(channel);
  if (rc == SSH_ERROR) {
      goto error;
  }

out:
  return (int)(origlen - len);

error:
  ssh_buffer_reinit(session->out_buffer);

  return SSH_ERROR;
}

uint32_t ssh_channel_window_size(ssh_channel channel) {
    return channel->remote_window;
}

/**
 * @brief Blocking write on a channel.
 *
 * @param[in]  channel  The channel to write to.
 *
 * @param[in]  data     A pointer to the data to write.
 *
 * @param[in]  len      The length of the buffer to write to.
 *
 * @return              The number of bytes written, SSH_ERROR on error.
 *
 * @see ssh_channel_read()
 */
int ssh_channel_write(ssh_channel channel, const void *data, uint32_t len) {
  return channel_write_common(channel, data, len, 0);
}

/**
 * @brief Check if the channel is open or not.
 *
 * @param[in]  channel  The channel to check.
 *
 * @return              0 if channel is closed, nonzero otherwise.
 *
 * @see ssh_channel_is_closed()
 */
int ssh_channel_is_open(ssh_channel channel) {
    if(channel == NULL) {
        return 0;
    }
    return (channel->state == SSH_CHANNEL_STATE_OPEN && channel->session->alive != 0);
}

/**
 * @brief Check if the channel is closed or not.
 *
 * @param[in]  channel  The channel to check.
 *
 * @return              0 if channel is opened, nonzero otherwise.
 *
 * @see ssh_channel_is_open()
 */
int ssh_channel_is_closed(ssh_channel channel) {
    if(channel == NULL) {
        return SSH_ERROR;
    }
    return (channel->state != SSH_CHANNEL_STATE_OPEN || channel->session->alive == 0);
}

/**
 * @brief Check if remote has sent an EOF.
 *
 * @param[in]  channel  The channel to check.
 *
 * @return              0 if there is no EOF, nonzero otherwise.
 */
int ssh_channel_is_eof(ssh_channel channel) {
  if(channel == NULL) {
      return SSH_ERROR;
  }
  if ((channel->stdout_buffer &&
        buffer_get_rest_len(channel->stdout_buffer) > 0) ||
      (channel->stderr_buffer &&
       buffer_get_rest_len(channel->stderr_buffer) > 0)) {
    return 0;
  }

  return (channel->remote_eof != 0);
}

/**
 * @brief Put the channel into blocking or nonblocking mode.
 *
 * @param[in]  channel  The channel to use.
 *
 * @param[in]  blocking A boolean for blocking or nonblocking.
 *
 * @warning    A side-effect of this is to put the whole session
 *             in non-blocking mode.
 * @see ssh_set_blocking()
 */
void ssh_channel_set_blocking(ssh_channel channel, int blocking) {
  if(channel == NULL) {
      return;
  }
  ssh_set_blocking(channel->session,blocking);
}

/**
 * @internal
 *
 * @brief handle a SSH_CHANNEL_SUCCESS packet and set the channel state.
 *
 * This works on SSH1 sessions too.
 */
SSH_PACKET_CALLBACK(ssh_packet_channel_success){
  ssh_channel channel;
  (void)type;
  (void)user;

  channel=channel_from_msg(session,packet);
  if (channel == NULL) {
    SSH_LOG(SSH_LOG_FUNCTIONS, "%s", ssh_get_error(session));
    return SSH_PACKET_USED;
  }

  SSH_LOG(SSH_LOG_PACKET,
      "Received SSH_CHANNEL_SUCCESS on channel (%d:%d)",
      channel->local_channel,
      channel->remote_channel);
  if(channel->request_state != SSH_CHANNEL_REQ_STATE_PENDING){
    SSH_LOG(SSH_LOG_RARE, "SSH_CHANNEL_SUCCESS received in incorrect state %d",
        channel->request_state);
  } else {
    channel->request_state=SSH_CHANNEL_REQ_STATE_ACCEPTED;
  }

  return SSH_PACKET_USED;
}

/**
 * @internal
 *
 * @brief Handle a SSH_CHANNEL_FAILURE packet and set the channel state.
 *
 * This works on SSH1 sessions too.
 */
SSH_PACKET_CALLBACK(ssh_packet_channel_failure){
  ssh_channel channel;
  (void)type;
  (void)user;

  channel=channel_from_msg(session,packet);
  if (channel == NULL) {
    SSH_LOG(SSH_LOG_FUNCTIONS, "%s", ssh_get_error(session));

    return SSH_PACKET_USED;
  }

  SSH_LOG(SSH_LOG_PACKET,
      "Received SSH_CHANNEL_FAILURE on channel (%d:%d)",
      channel->local_channel,
      channel->remote_channel);
  if(channel->request_state != SSH_CHANNEL_REQ_STATE_PENDING){
    SSH_LOG(SSH_LOG_RARE, "SSH_CHANNEL_FAILURE received in incorrect state %d",
        channel->request_state);
  } else {
    channel->request_state=SSH_CHANNEL_REQ_STATE_DENIED;
  }

  return SSH_PACKET_USED;
}

static int ssh_channel_request_termination(void *c){
  ssh_channel channel = (ssh_channel)c;
  if(channel->request_state != SSH_CHANNEL_REQ_STATE_PENDING ||
      channel->session->session_state == SSH_SESSION_STATE_ERROR)
    return 1;
  else
    return 0;
}

static int channel_request(ssh_channel channel, const char *request,
    ssh_buffer buffer, int reply) {
  ssh_session session = channel->session;
  int rc = SSH_ERROR;
  int ret;

  switch(channel->request_state){
  case SSH_CHANNEL_REQ_STATE_NONE:
    break;
  default:
    goto pending;
  }

  ret = ssh_buffer_pack(session->out_buffer,
                        "bdsb",
                        SSH2_MSG_CHANNEL_REQUEST,
                        channel->remote_channel,
                        request,
                        reply == 0 ? 0 : 1);
  if (ret != SSH_OK) {
    ssh_set_error_oom(session);
    goto error;
  }

  if (buffer != NULL) {
    if (ssh_buffer_add_data(session->out_buffer, buffer_get_rest(buffer),
        buffer_get_rest_len(buffer)) < 0) {
      ssh_set_error_oom(session);
      goto error;
    }
  }
  channel->request_state = SSH_CHANNEL_REQ_STATE_PENDING;
  if (packet_send(session) == SSH_ERROR) {
    return rc;
  }

  SSH_LOG(SSH_LOG_PACKET,
      "Sent a SSH_MSG_CHANNEL_REQUEST %s", request);
  if (reply == 0) {
    channel->request_state = SSH_CHANNEL_REQ_STATE_NONE;
    return SSH_OK;
  }
pending:
  rc = ssh_handle_packets_termination(session,
                                      SSH_TIMEOUT_DEFAULT,
                                      ssh_channel_request_termination,
                                      channel);

  if(session->session_state == SSH_SESSION_STATE_ERROR || rc == SSH_ERROR) {
      channel->request_state = SSH_CHANNEL_REQ_STATE_ERROR;
  }
  /* we received something */
  switch (channel->request_state){
    case SSH_CHANNEL_REQ_STATE_ERROR:
      rc=SSH_ERROR;
      break;
    case SSH_CHANNEL_REQ_STATE_DENIED:
      ssh_set_error(session, SSH_REQUEST_DENIED,
          "Channel request %s failed", request);
      rc=SSH_ERROR;
      break;
    case SSH_CHANNEL_REQ_STATE_ACCEPTED:
      SSH_LOG(SSH_LOG_PROTOCOL,
          "Channel request %s success",request);
      rc=SSH_OK;
      break;
    case SSH_CHANNEL_REQ_STATE_PENDING:
      rc = SSH_AGAIN;
      return rc;
    case SSH_CHANNEL_REQ_STATE_NONE:
      /* Never reached */
      ssh_set_error(session, SSH_FATAL, "Invalid state in channel_request()");
      rc=SSH_ERROR;
      break;
  }
  channel->request_state=SSH_CHANNEL_REQ_STATE_NONE;

  return rc;
error:
  ssh_buffer_reinit(session->out_buffer);

  return rc;
}

/**
 * @brief Request a pty with a specific type and size.
 *
 * @param[in]  channel  The channel to sent the request.
 *
 * @param[in]  terminal The terminal type ("vt100, xterm,...").
 *
 * @param[in]  col      The number of columns.
 *
 * @param[in]  row      The number of rows.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 */
int ssh_channel_request_pty_size(ssh_channel channel, const char *terminal,
    int col, int row) {
  ssh_session session;
  ssh_buffer buffer = NULL;
  int rc = SSH_ERROR;

  if(channel == NULL) {
      return SSH_ERROR;
  }
  session = channel->session;

  if(terminal == NULL) {
      ssh_set_error_invalid(channel->session);
      return rc;
  }

#ifdef WITH_SSH1
  if (channel->version==1) {
    rc = channel_request_pty_size1(channel,terminal, col, row);

    return rc;
    }
#endif
  switch(channel->request_state){
  case SSH_CHANNEL_REQ_STATE_NONE:
    break;
  default:
    goto pending;
  }

  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    ssh_set_error_oom(session);
    goto error;
  }

  rc = ssh_buffer_pack(buffer,
                       "sdddddb",
                       terminal,
                       col,
                       row,
                       0, /* pix */
                       0, /* pix */
                       1, /* add a 0byte string */
                       0);

  if (rc != SSH_OK) {
    ssh_set_error_oom(session);
    goto error;
  }
pending:
  rc = channel_request(channel, "pty-req", buffer, 1);
error:
  ssh_buffer_free(buffer);

  return rc;
}

/**
 * @brief Request a PTY.
 *
 * @param[in]  channel  The channel to send the request.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 *
 * @see ssh_channel_request_pty_size()
 */
int ssh_channel_request_pty(ssh_channel channel) {
  return ssh_channel_request_pty_size(channel, "xterm", 80, 24);
}

/**
 * @brief Change the size of the terminal associated to a channel.
 *
 * @param[in]  channel  The channel to change the size.
 *
 * @param[in]  cols     The new number of columns.
 *
 * @param[in]  rows     The new number of rows.
 *
 * @return              SSH_OK on success, SSH_ERROR if an error occurred.
 *
 * @warning Do not call it from a signal handler if you are not sure any other
 *          libssh function using the same channel/session is running at same
 *          time (not 100% threadsafe).
 */
int ssh_channel_change_pty_size(ssh_channel channel, int cols, int rows) {
  ssh_session session = channel->session;
  ssh_buffer buffer = NULL;
  int rc = SSH_ERROR;

#ifdef WITH_SSH1
  if (channel->version == 1) {
    rc = channel_change_pty_size1(channel,cols,rows);

    return rc;
  }
#endif

  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    ssh_set_error_oom(session);
    goto error;
  }

  rc = ssh_buffer_pack(buffer,
                       "dddd",
                       cols,
                       rows,
                       0, /* pix */
                       0 /* pix */);
  if (rc != SSH_OK) {
    ssh_set_error_oom(session);
    goto error;
  }

  rc = channel_request(channel, "window-change", buffer, 0);
error:
  ssh_buffer_free(buffer);

  return rc;
}

/**
 * @brief Request a shell.
 *
 * @param[in]  channel  The channel to send the request.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 */
int ssh_channel_request_shell(ssh_channel channel) {
    if(channel == NULL) {
        return SSH_ERROR;
    }
#ifdef WITH_SSH1
  if (channel->version == 1) {
    return channel_request_shell1(channel);
  }
#endif
  return channel_request(channel, "shell", NULL, 1);
}

/**
 * @brief Request a subsystem (for example "sftp").
 *
 * @param[in]  channel  The channel to send the request.
 *
 * @param[in]  subsys   The subsystem to request (for example "sftp").
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 *
 * @warning You normally don't have to call it for sftp, see sftp_new().
 */
int ssh_channel_request_subsystem(ssh_channel channel, const char *subsys) {
  ssh_buffer buffer = NULL;
  int rc = SSH_ERROR;

  if(channel == NULL) {
      return SSH_ERROR;
  }
  if(subsys == NULL) {
      ssh_set_error_invalid(channel->session);
      return rc;
  }
  switch(channel->request_state){
  case SSH_CHANNEL_REQ_STATE_NONE:
    break;
  default:
    goto pending;
  }

  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    ssh_set_error_oom(channel->session);
    goto error;
  }

  rc = ssh_buffer_pack(buffer, "s", subsys);
  if (rc != SSH_OK) {
    ssh_set_error_oom(channel->session);
    goto error;
  }
pending:
  rc = channel_request(channel, "subsystem", buffer, 1);
error:
  ssh_buffer_free(buffer);

  return rc;
}

int ssh_channel_request_sftp( ssh_channel channel){
    if(channel == NULL) {
        return SSH_ERROR;
    }
    return ssh_channel_request_subsystem(channel, "sftp");
}

static char *generate_cookie(void) {
  static const char *hex = "0123456789abcdef";
  char s[36];
  unsigned char rnd[16];
  int i;

  ssh_get_random(rnd,sizeof(rnd),0);
  for (i = 0; i < 16; i++) {
    s[i*2] = hex[rnd[i] & 0x0f];
    s[i*2+1] = hex[rnd[i] >> 4];
  }
  s[32] = '\0';
  return strdup(s);
}

/**
 * @brief Sends the "x11-req" channel request over an existing session channel.
 *
 * This will enable redirecting the display of the remote X11 applications to
 * local X server over an secure tunnel.
 *
 * @param[in]  channel  An existing session channel where the remote X11
 *                      applications are going to be executed.
 *
 * @param[in]  single_connection A boolean to mark only one X11 app will be
 *                               redirected.
 *
 * @param[in]  protocol A x11 authentication protocol. Pass NULL to use the
 *                      default value MIT-MAGIC-COOKIE-1.
 *
 * @param[in]  cookie   A x11 authentication cookie. Pass NULL to generate
 *                      a random cookie.
 *
 * @param[in] screen_number The screen number.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 */
int ssh_channel_request_x11(ssh_channel channel, int single_connection, const char *protocol,
    const char *cookie, int screen_number) {
  ssh_buffer buffer = NULL;
  char *c = NULL;
  int rc = SSH_ERROR;

  if(channel == NULL) {
      return SSH_ERROR;
  }
  switch(channel->request_state){
  case SSH_CHANNEL_REQ_STATE_NONE:
    break;
  default:
    goto pending;
  }

  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    ssh_set_error_oom(channel->session);
    goto error;
  }

  if (cookie == NULL) {
    c = generate_cookie();
    if (c == NULL) {
      ssh_set_error_oom(channel->session);
      goto error;
    }
  }

  rc = ssh_buffer_pack(buffer,
                       "bssd",
                       single_connection == 0 ? 0 : 1,
                       protocol ? protocol : "MIT-MAGIC-COOKIE-1",
                       cookie ? cookie : c,
                       screen_number);
  if (c != NULL){
      SAFE_FREE(c);
  }
  if (rc != SSH_OK) {
    ssh_set_error_oom(channel->session);
    goto error;
  }
pending:
  rc = channel_request(channel, "x11-req", buffer, 1);

error:
  ssh_buffer_free(buffer);
  return rc;
}

static ssh_channel ssh_channel_accept(ssh_session session, int channeltype,
    int timeout_ms, int *destination_port) {
#ifndef _WIN32
  static const struct timespec ts = {
    .tv_sec = 0,
    .tv_nsec = 50000000 /* 50ms */
  };
#endif
  ssh_message msg = NULL;
  ssh_channel channel = NULL;
  struct ssh_iterator *iterator;
  int t;

  /*
   * We sleep for 50 ms in ssh_handle_packets() and later sleep for
   * 50 ms. So we need to decrement by 100 ms.
   */
  for (t = timeout_ms; t >= 0; t -= 100) {
    if (timeout_ms == 0) {
        ssh_handle_packets(session, 0);
    } else {
        ssh_handle_packets(session, 50);
    }

    if (session->ssh_message_list) {
      iterator = ssh_list_get_iterator(session->ssh_message_list);
      while (iterator) {
        msg = (ssh_message)iterator->data;
        if (ssh_message_type(msg) == SSH_REQUEST_CHANNEL_OPEN &&
            ssh_message_subtype(msg) == channeltype) {
          ssh_list_remove(session->ssh_message_list, iterator);
          channel = ssh_message_channel_request_open_reply_accept(msg);
          if(destination_port) {
            *destination_port=msg->channel_request_open.destination_port;
          }

          ssh_message_free(msg);
          return channel;
        }
        iterator = iterator->next;
      }
    }
    if(t>0){
#ifdef _WIN32
      Sleep(50); /* 50ms */
#else
      nanosleep(&ts, NULL);
#endif
    }
  }

  ssh_set_error(session, SSH_NO_ERROR, "No channel request of this type from server");
  return NULL;
}

/**
 * @brief Accept an X11 forwarding channel.
 *
 * @param[in]  channel  An x11-enabled session channel.
 *
 * @param[in]  timeout_ms Timeout in milliseconds.
 *
 * @return              A newly created channel, or NULL if no X11 request from
 *                      the server.
 */
ssh_channel ssh_channel_accept_x11(ssh_channel channel, int timeout_ms) {
  return ssh_channel_accept(channel->session, SSH_CHANNEL_X11, timeout_ms, NULL);
}

/**
 * @internal
 *
 * @brief Handle a SSH_REQUEST_SUCCESS packet normally sent after a global
 * request.
 */
SSH_PACKET_CALLBACK(ssh_request_success){
  (void)type;
  (void)user;
  (void)packet;

  SSH_LOG(SSH_LOG_PACKET,
      "Received SSH_REQUEST_SUCCESS");
  if(session->global_req_state != SSH_CHANNEL_REQ_STATE_PENDING){
    SSH_LOG(SSH_LOG_RARE, "SSH_REQUEST_SUCCESS received in incorrect state %d",
        session->global_req_state);
  } else {
    session->global_req_state=SSH_CHANNEL_REQ_STATE_ACCEPTED;
  }

  return SSH_PACKET_USED;
}

/**
 * @internal
 *
 * @brief Handle a SSH_REQUEST_DENIED packet normally sent after a global
 * request.
 */
SSH_PACKET_CALLBACK(ssh_request_denied){
  (void)type;
  (void)user;
  (void)packet;

  SSH_LOG(SSH_LOG_PACKET,
      "Received SSH_REQUEST_FAILURE");
  if(session->global_req_state != SSH_CHANNEL_REQ_STATE_PENDING){
    SSH_LOG(SSH_LOG_RARE, "SSH_REQUEST_DENIED received in incorrect state %d",
        session->global_req_state);
  } else {
    session->global_req_state=SSH_CHANNEL_REQ_STATE_DENIED;
  }

  return SSH_PACKET_USED;

}

static int ssh_global_request_termination(void *s){
  ssh_session session = (ssh_session) s;
  if (session->global_req_state != SSH_CHANNEL_REQ_STATE_PENDING ||
      session->session_state == SSH_SESSION_STATE_ERROR)
    return 1;
  else
    return 0;
}

/**
 * @internal
 *
 * @brief Send a global request (needed for forward listening) and wait for the
 * result.
 *
 * @param[in]  session  The SSH session handle.
 *
 * @param[in]  request  The type of request (defined in RFC).
 *
 * @param[in]  buffer   Additional data to put in packet.
 *
 * @param[in]  reply    Set if you expect a reply from server.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 */
static int global_request(ssh_session session, const char *request,
    ssh_buffer buffer, int reply) {
  int rc;

  switch (session->global_req_state) {
  case SSH_CHANNEL_REQ_STATE_NONE:
    break;
  default:
    goto pending;
  }

  rc = ssh_buffer_pack(session->out_buffer,
                       "bsb",
                       SSH2_MSG_GLOBAL_REQUEST,
                       request,
                       reply == 0 ? 0 : 1);
  if (rc != SSH_OK){
      ssh_set_error_oom(session);
      rc = SSH_ERROR;
      goto error;
  }

  if (buffer != NULL) {
      rc = ssh_buffer_add_data(session->out_buffer,
                           buffer_get_rest(buffer),
                           buffer_get_rest_len(buffer));
      if (rc < 0) {
          ssh_set_error_oom(session);
          rc = SSH_ERROR;
          goto error;
      }
  }

  session->global_req_state = SSH_CHANNEL_REQ_STATE_PENDING;
  rc = packet_send(session);
  if (rc == SSH_ERROR) {
      return rc;
  }

  SSH_LOG(SSH_LOG_PACKET,
      "Sent a SSH_MSG_GLOBAL_REQUEST %s", request);

  if (reply == 0) {
      session->global_req_state = SSH_CHANNEL_REQ_STATE_NONE;

      return SSH_OK;
  }
pending:
  rc = ssh_handle_packets_termination(session,
                                      SSH_TIMEOUT_DEFAULT,
                                      ssh_global_request_termination,
                                      session);

  if(rc==SSH_ERROR || session->session_state == SSH_SESSION_STATE_ERROR){
    session->global_req_state = SSH_CHANNEL_REQ_STATE_ERROR;
  }
  switch(session->global_req_state){
    case SSH_CHANNEL_REQ_STATE_ACCEPTED:
      SSH_LOG(SSH_LOG_PROTOCOL, "Global request %s success",request);
      rc=SSH_OK;
      break;
    case SSH_CHANNEL_REQ_STATE_DENIED:
      SSH_LOG(SSH_LOG_PACKET,
          "Global request %s failed", request);
      ssh_set_error(session, SSH_REQUEST_DENIED,
          "Global request %s failed", request);
      rc=SSH_ERROR;
      break;
    case SSH_CHANNEL_REQ_STATE_ERROR:
    case SSH_CHANNEL_REQ_STATE_NONE:
      rc = SSH_ERROR;
      break;
    case SSH_CHANNEL_REQ_STATE_PENDING:
      return SSH_AGAIN;
  }
  session->global_req_state = SSH_CHANNEL_REQ_STATE_NONE;

  return rc;
error:
  ssh_buffer_reinit(session->out_buffer);

  return rc;
}

/**
 * @brief Sends the "tcpip-forward" global request to ask the server to begin
 *        listening for inbound connections.
 *
 * @param[in]  session  The ssh session to send the request.
 *
 * @param[in]  address  The address to bind to on the server. Pass NULL to bind
 *                      to all available addresses on all protocol families
 *                      supported by the server.
 *
 * @param[in]  port     The port to bind to on the server. Pass 0 to ask the
 *                      server to allocate the next available unprivileged port
 *                      number
 *
 * @param[in]  bound_port The pointer to get actual bound port. Pass NULL to
 *                        ignore.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 **/
int ssh_channel_listen_forward(ssh_session session,
                               const char *address,
                               int port,
                               int *bound_port)
{
  ssh_buffer buffer = NULL;
  int rc = SSH_ERROR;

  if(session->global_req_state != SSH_CHANNEL_REQ_STATE_NONE)
    goto pending;

  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    ssh_set_error_oom(session);
    goto error;
  }

  rc = ssh_buffer_pack(buffer,
                       "sd",
                       address ? address : "",
                       port);
  if (rc != SSH_OK){
    ssh_set_error_oom(session);
    goto error;
  }
pending:
  rc = global_request(session, "tcpip-forward", buffer, 1);

  /* TODO: FIXME no guarantee the last packet we received contains
   * that info */
  if (rc == SSH_OK && port == 0 && bound_port != NULL) {
    rc = ssh_buffer_unpack(session->in_buffer, "d", bound_port);
    if (rc != SSH_OK)
        *bound_port = 0;
  }

error:
  ssh_buffer_free(buffer);
  return rc;
}

/* DEPRECATED */
ssh_channel ssh_forward_accept(ssh_session session, int timeout_ms) {
  return ssh_channel_accept(session, SSH_CHANNEL_FORWARDED_TCPIP, timeout_ms, NULL);
}

/**
 * @brief Accept an incoming TCP/IP forwarding channel and get information
 * about incomming connection
 * @param[in]  session    The ssh session to use.
 *
 * @param[in]  timeout_ms A timeout in milliseconds.
 *
 * @param[in]  destination_port A pointer to destination port or NULL.
 *
 * @return Newly created channel, or NULL if no incoming channel request from
 *         the server
 */
ssh_channel ssh_channel_accept_forward(ssh_session session, int timeout_ms, int* destination_port) {
  return ssh_channel_accept(session, SSH_CHANNEL_FORWARDED_TCPIP, timeout_ms, destination_port);
}

/**
 * @brief Sends the "cancel-tcpip-forward" global request to ask the server to
 *        cancel the tcpip-forward request.
 *
 * @param[in]  session  The ssh session to send the request.
 *
 * @param[in]  address  The bound address on the server.
 *
 * @param[in]  port     The bound port on the server.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 */
int ssh_channel_cancel_forward(ssh_session session,
                               const char *address,
                               int port)
{
  ssh_buffer buffer = NULL;
  int rc = SSH_ERROR;

  if(session->global_req_state != SSH_CHANNEL_REQ_STATE_NONE)
    goto pending;

  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    ssh_set_error_oom(session);
    goto error;
  }

  rc = ssh_buffer_pack(buffer, "sd",
                       address ? address : "",
                       port);
  if (rc != SSH_OK){
      ssh_set_error_oom(session);
      goto error;
  }
pending:
  rc = global_request(session, "cancel-tcpip-forward", buffer, 1);

error:
  ssh_buffer_free(buffer);
  return rc;
}

int ssh_forward_cancel(ssh_session session, const char *address, int port) {
    return ssh_channel_cancel_forward(session, address, port);
}

/**
 * @brief Set environment variables.
 *
 * @param[in]  channel  The channel to set the environment variables.
 *
 * @param[in]  name     The name of the variable.
 *
 * @param[in]  value    The value to set.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 * @warning Some environment variables may be refused by security reasons.
 */
int ssh_channel_request_env(ssh_channel channel, const char *name, const char *value) {
  ssh_buffer buffer = NULL;
  int rc = SSH_ERROR;

  if(channel == NULL) {
      return SSH_ERROR;
  }
  if(name == NULL || value == NULL) {
      ssh_set_error_invalid(channel->session);
      return rc;
  }
  switch(channel->request_state){
  case SSH_CHANNEL_REQ_STATE_NONE:
    break;
  default:
    goto pending;
  }
  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    ssh_set_error_oom(channel->session);
    goto error;
  }

  rc = ssh_buffer_pack(buffer,
                       "ss",
                       name,
                       value);
  if (rc != SSH_OK){
    ssh_set_error_oom(channel->session);
    goto error;
  }
pending:
  rc = channel_request(channel, "env", buffer,1);
error:
  ssh_buffer_free(buffer);

  return rc;
}

/**
 * @brief Run a shell command without an interactive shell.
 *
 * This is similar to 'sh -c command'.
 *
 * @param[in]  channel  The channel to execute the command.
 *
 * @param[in]  cmd      The command to execute
 *                      (e.g. "ls ~/ -al | grep -i reports").
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 *
 * Example:
@code
   rc = channel_request_exec(channel, "ps aux");
   if (rc > 0) {
       return -1;
   }

   while ((rc = channel_read(channel, buffer, sizeof(buffer), 0)) > 0) {
       if (fwrite(buffer, 1, rc, stdout) != (unsigned int) rc) {
           return -1;
       }
   }
@endcode
 *
 * @see ssh_channel_request_shell()
 */
int ssh_channel_request_exec(ssh_channel channel, const char *cmd) {
  ssh_buffer buffer = NULL;
  int rc = SSH_ERROR;

  if(channel == NULL) {
      return SSH_ERROR;
  }
  if(cmd == NULL) {
      ssh_set_error_invalid(channel->session);
      return rc;
  }

#ifdef WITH_SSH1
  if (channel->version == 1) {
    return channel_request_exec1(channel, cmd);
  }
#endif
  switch(channel->request_state){
  case SSH_CHANNEL_REQ_STATE_NONE:
    break;
  default:
    goto pending;
  }
  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    ssh_set_error_oom(channel->session);
    goto error;
  }

  rc = ssh_buffer_pack(buffer, "s", cmd);

  if (rc != SSH_OK) {
    ssh_set_error_oom(channel->session);
    goto error;
  }
pending:
  rc = channel_request(channel, "exec", buffer, 1);
error:
  ssh_buffer_free(buffer);
  return rc;
}


/**
 * @brief Send a signal to remote process (as described in RFC 4254, section 6.9).
 *
 * Sends a signal 'sig' to the remote process.
 * Note, that remote system may not support signals concept.
 * In such a case this request will be silently ignored.
 * Only SSH-v2 is supported (I'm not sure about SSH-v1).
 *
 * OpenSSH doesn't support signals yet, see:
 * https://bugzilla.mindrot.org/show_bug.cgi?id=1424
 *
 * @param[in]  channel  The channel to send signal.
 *
 * @param[in]  sig      The signal to send (without SIG prefix)
 *                      \n\n
 *                      SIGABRT  -> ABRT \n
 *                      SIGALRM  -> ALRM \n
 *                      SIGFPE   -> FPE  \n
 *                      SIGHUP   -> HUP  \n
 *                      SIGILL   -> ILL  \n
 *                      SIGINT   -> INT  \n
 *                      SIGKILL  -> KILL \n
 *                      SIGPIPE  -> PIPE \n
 *                      SIGQUIT  -> QUIT \n
 *                      SIGSEGV  -> SEGV \n
 *                      SIGTERM  -> TERM \n
 *                      SIGUSR1  -> USR1 \n
 *                      SIGUSR2  -> USR2 \n
 *
 * @return              SSH_OK on success, SSH_ERROR if an error occurred
 *                      (including attempts to send signal via SSH-v1 session).
 */
int ssh_channel_request_send_signal(ssh_channel channel, const char *sig) {
  ssh_buffer buffer = NULL;
  int rc = SSH_ERROR;

  if(channel == NULL) {
      return SSH_ERROR;
  }
  if(sig == NULL) {
      ssh_set_error_invalid(channel->session);
      return rc;
  }

#ifdef WITH_SSH1
  if (channel->version == 1) {
    return SSH_ERROR; // TODO: Add support for SSH-v1 if possible.
  }
#endif

  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    ssh_set_error_oom(channel->session);
    goto error;
  }

  rc = ssh_buffer_pack(buffer, "s", sig);
  if (rc != SSH_OK) {
    ssh_set_error_oom(channel->session);
    goto error;
  }

  rc = channel_request(channel, "signal", buffer, 0);
error:
  ssh_buffer_free(buffer);
  return rc;
}


/**
 * @brief Read data from a channel into a buffer.
 *
 * @param[in]  channel  The channel to read from.
 *
 * @param[in]  buffer   The buffer which will get the data.
 *
 * @param[in]  count    The count of bytes to be read. If it is bigger than 0,
 *                      the exact size will be read, else (bytes=0) it will
 *                      return once anything is available.
 *
 * @param is_stderr     A boolean value to mark reading from the stderr stream.
 *
 * @return              The number of bytes read, 0 on end of file or SSH_ERROR
 *                      on error.
 * @deprecated          Please use ssh_channel_read instead
 * @warning             This function doesn't work in nonblocking/timeout mode
 * @see ssh_channel_read
 */
int channel_read_buffer(ssh_channel channel, ssh_buffer buffer, uint32_t count,
    int is_stderr) {
  ssh_session session;
  char buffer_tmp[8192];
  int r;
  uint32_t total=0;

  if(channel == NULL) {
      return SSH_ERROR;
  }
  session = channel->session;

  if(buffer == NULL) {
      ssh_set_error_invalid(channel->session);
      return SSH_ERROR;
  }

  ssh_buffer_reinit(buffer);
  if(count==0){
    do {
      r=ssh_channel_poll(channel, is_stderr);
      if(r < 0){
        return r;
      }
      if(r > 0){
        r=ssh_channel_read(channel, buffer_tmp, r, is_stderr);
        if(r < 0){
          return r;
        }
        if(ssh_buffer_add_data(buffer,buffer_tmp,r) < 0){
          ssh_set_error_oom(session);
          r = SSH_ERROR;
        }

        return r;
      }
      if(ssh_channel_is_eof(channel)){
        return 0;
      }
      ssh_handle_packets(channel->session, SSH_TIMEOUT_INFINITE);
    } while (r == 0);
  }
  while(total < count){
    r=ssh_channel_read(channel, buffer_tmp, sizeof(buffer_tmp), is_stderr);
    if(r<0){
      return r;
    }
    if(r==0){
      return total;
    }
    if (ssh_buffer_add_data(buffer,buffer_tmp,r) < 0) {
      ssh_set_error_oom(session);

      return SSH_ERROR;
    }
    total += r;
  }

  return total;
}

struct ssh_channel_read_termination_struct {
  ssh_channel channel;
  uint32_t count;
  ssh_buffer buffer;
};

static int ssh_channel_read_termination(void *s){
  struct ssh_channel_read_termination_struct *ctx = s;
  if (buffer_get_rest_len(ctx->buffer) >= ctx->count ||
      ctx->channel->remote_eof ||
      ctx->channel->session->session_state == SSH_SESSION_STATE_ERROR)
    return 1;
  else
    return 0;
}

/* TODO FIXME Fix the delayed close thing */
/* TODO FIXME Fix the blocking behaviours */

/**
 * @brief Reads data from a channel.
 *
 * @param[in]  channel  The channel to read from.
 *
 * @param[in]  dest     The destination buffer which will get the data.
 *
 * @param[in]  count    The count of bytes to be read.
 *
 * @param[in]  is_stderr A boolean value to mark reading from the stderr flow.
 *
 * @return              The number of bytes read, 0 on end of file or SSH_ERROR
 *                      on error. In nonblocking mode it Can return 0 if no data
 *                      is available or SSH_AGAIN.
 *
 * @warning This function may return less than count bytes of data, and won't
 *          block until count bytes have been read.
 * @warning The read function using a buffer has been renamed to
 *          channel_read_buffer().
 */
int ssh_channel_read(ssh_channel channel, void *dest, uint32_t count, int is_stderr)
{
    return ssh_channel_read_timeout(channel, dest, count, is_stderr, -1);
}

/**
 * @brief Reads data from a channel.
 *
 * @param[in]  channel     The channel to read from.
 *
 * @param[in]  dest        The destination buffer which will get the data.
 *
 * @param[in]  count       The count of bytes to be read.
 *
 * @param[in]  is_stderr   A boolean value to mark reading from the stderr flow.
 *
 * @param[in]  timeout_ms  A timeout in milliseconds. A value of -1 means
 *                         infinite timeout.
 *
 * @return              The number of bytes read, 0 on end of file or SSH_ERROR
 *                      on error. In nonblocking mode it Can return 0 if no data
 *                      is available or SSH_AGAIN.
 *
 * @warning This function may return less than count bytes of data, and won't
 *          block until count bytes have been read.
 * @warning The read function using a buffer has been renamed to
 *          channel_read_buffer().
 */
int ssh_channel_read_timeout(ssh_channel channel,
                             void *dest,
                             uint32_t count,
                             int is_stderr,
                             int timeout)
{
  ssh_session session;
  ssh_buffer stdbuf;
  uint32_t len;
  struct ssh_channel_read_termination_struct ctx;
  int rc;

  if(channel == NULL) {
      return SSH_ERROR;
  }
  if(dest == NULL) {
      ssh_set_error_invalid(channel->session);
      return SSH_ERROR;
  }

  session = channel->session;
  stdbuf = channel->stdout_buffer;

  if (count == 0) {
    return 0;
  }

  if (is_stderr) {
    stdbuf=channel->stderr_buffer;
  }

  /*
   * We may have problem if the window is too small to accept as much data
   * as asked
   */
  SSH_LOG(SSH_LOG_PACKET,
      "Read (%d) buffered : %d bytes. Window: %d",
      count,
      buffer_get_rest_len(stdbuf),
      channel->local_window);

  if (count > buffer_get_rest_len(stdbuf) + channel->local_window) {
    if (grow_window(session, channel, count - buffer_get_rest_len(stdbuf)) < 0) {
      return -1;
    }
  }

  /* block reading until at least one byte has been read
  *  and ignore the trivial case count=0
  */
  ctx.channel = channel;
  ctx.buffer = stdbuf;
  ctx.count = 1;

  if (timeout < 0) {
      timeout = SSH_TIMEOUT_DEFAULT;
  }

  rc = ssh_handle_packets_termination(session,
                                      timeout,
                                      ssh_channel_read_termination,
                                      &ctx);
  if (rc == SSH_ERROR){
    return rc;
  }
  if (channel->session->session_state == SSH_SESSION_STATE_ERROR){
      return SSH_ERROR;
  }
  if (channel->remote_eof && buffer_get_rest_len(stdbuf) == 0) {
    return 0;
  }
  len = buffer_get_rest_len(stdbuf);
  /* Read count bytes if len is greater, everything otherwise */
  len = (len > count ? count : len);
  memcpy(dest, buffer_get_rest(stdbuf), len);
  buffer_pass_bytes(stdbuf,len);
  if (channel->counter != NULL) {
      channel->counter->in_bytes += len;
  }
  /* Authorize some buffering while userapp is busy */
  if (channel->local_window < WINDOWLIMIT) {
    if (grow_window(session, channel, 0) < 0) {
      return -1;
    }
  }

  return len;
}

/**
 * @brief Do a nonblocking read on the channel.
 *
 * A nonblocking read on the specified channel. it will return <= count bytes of
 * data read atomically.
 *
 * @param[in]  channel  The channel to read from.
 *
 * @param[in]  dest     A pointer to a destination buffer.
 *
 * @param[in]  count    The count of bytes of data to be read.
 *
 * @param[in]  is_stderr A boolean to select the stderr stream.
 *
 * @return              The number of bytes read, 0 if nothing is available or
 *                      SSH_ERROR on error.
 *
 * @warning Don't forget to check for EOF as it would return 0 here.
 *
 * @see ssh_channel_is_eof()
 */
int ssh_channel_read_nonblocking(ssh_channel channel, void *dest, uint32_t count,
    int is_stderr) {
  ssh_session session;
  int to_read;
  int rc;
  int blocking;

  if(channel == NULL) {
      return SSH_ERROR;
  }
  if(dest == NULL) {
      ssh_set_error_invalid(channel->session);
      return SSH_ERROR;
  }

  session = channel->session;

  to_read = ssh_channel_poll(channel, is_stderr);

  if (to_read <= 0) {
      if (channel->session->session_state == SSH_SESSION_STATE_ERROR){
          return SSH_ERROR;
      }

      return to_read; /* may be an error code */
  }

  if (to_read > (int)count) {
    to_read = (int)count;
  }
  blocking = ssh_is_blocking(session);
  ssh_set_blocking(session, 0);
  rc = ssh_channel_read(channel, dest, to_read, is_stderr);
  ssh_set_blocking(session,blocking);

  return rc;
}

/**
 * @brief Polls a channel for data to read.
 *
 * @param[in]  channel  The channel to poll.
 *
 * @param[in]  is_stderr A boolean to select the stderr stream.
 *
 * @return              The number of bytes available for reading, 0 if nothing
 *                      is available or SSH_ERROR on error.
 *
 * @warning When the channel is in EOF state, the function returns SSH_EOF.
 *
 * @see ssh_channel_is_eof()
 */
int ssh_channel_poll(ssh_channel channel, int is_stderr){
  ssh_buffer stdbuf;

  if(channel == NULL) {
      return SSH_ERROR;
  }

  stdbuf = channel->stdout_buffer;

  if (is_stderr) {
    stdbuf = channel->stderr_buffer;
  }

  if (buffer_get_rest_len(stdbuf) == 0 && channel->remote_eof == 0) {
    if (channel->session->session_state == SSH_SESSION_STATE_ERROR){
      return SSH_ERROR;
    }
    if (ssh_handle_packets(channel->session, SSH_TIMEOUT_NONBLOCKING)==SSH_ERROR) {
      return SSH_ERROR;
    }
  }

  if (buffer_get_rest_len(stdbuf) > 0){
  	return buffer_get_rest_len(stdbuf);
  }

  if (channel->remote_eof) {
    return SSH_EOF;
  }

  return buffer_get_rest_len(stdbuf);
}

/**
 * @brief Polls a channel for data to read, waiting for a certain timeout.
 *
 * @param[in]  channel   The channel to poll.
 * @param[in]  timeout   Set an upper limit on the time for which this function
 *                       will block, in milliseconds. Specifying a negative value
 *                       means an infinite timeout. This parameter is passed to
 *                       the poll() function.
 * @param[in]  is_stderr A boolean to select the stderr stream.
 *
 * @return              The number of bytes available for reading,
 *                      0 if nothing is available (timeout elapsed),
 *                      SSH_EOF on end of file,
 *                      SSH_ERROR on error.
 *
 * @warning When the channel is in EOF state, the function returns SSH_EOF.
 *
 * @see ssh_channel_is_eof()
 */
int ssh_channel_poll_timeout(ssh_channel channel, int timeout, int is_stderr){
  ssh_session session;
  ssh_buffer stdbuf;
  struct ssh_channel_read_termination_struct ctx;
  int rc;

  if(channel == NULL) {
      return SSH_ERROR;
  }

  session = channel->session;
  stdbuf = channel->stdout_buffer;

  if (is_stderr) {
    stdbuf = channel->stderr_buffer;
  }
  ctx.buffer = stdbuf;
  ctx.channel = channel;
  ctx.count = 1;
  rc = ssh_handle_packets_termination(channel->session, timeout,
      ssh_channel_read_termination, &ctx);
  if(rc ==SSH_ERROR || session->session_state == SSH_SESSION_STATE_ERROR){
    rc = SSH_ERROR;
    goto end;
  }
  rc = buffer_get_rest_len(stdbuf);
  if(rc > 0)
    goto end;
  if (channel->remote_eof)
    rc = SSH_EOF;
end:
  return rc;
}

/**
 * @brief Recover the session in which belongs a channel.
 *
 * @param[in]  channel  The channel to recover the session from.
 *
 * @return              The session pointer.
 */
ssh_session ssh_channel_get_session(ssh_channel channel) {
  if(channel == NULL) {
      return NULL;
  }

  return channel->session;
}

static int ssh_channel_exit_status_termination(void *c){
  ssh_channel channel = c;
  if(channel->exit_status != -1 ||
      /* When a channel is closed, no exit status message can
       * come anymore */
      (channel->flags & SSH_CHANNEL_FLAG_CLOSED_REMOTE) ||
      channel->session->session_state == SSH_SESSION_STATE_ERROR)
    return 1;
  else
    return 0;
}

/**
 * @brief Get the exit status of the channel (error code from the executed
 *        instruction).
 *
 * @param[in]  channel  The channel to get the status from.
 *
 * @returns             The exit status, -1 if no exit status has been returned
 *                      (yet).
 * @warning             This function may block until a timeout (or never)
 *                      if the other side is not willing to close the channel.
 *
 * If you're looking for an async handling of this register a callback for the
 * exit status.
 *
 * @see ssh_channel_exit_status_callback
 */
int ssh_channel_get_exit_status(ssh_channel channel) {
  int rc;
  if(channel == NULL) {
      return SSH_ERROR;
  }
  rc = ssh_handle_packets_termination(channel->session,
                                      SSH_TIMEOUT_DEFAULT,
                                      ssh_channel_exit_status_termination,
                                      channel);
  if (rc == SSH_ERROR || channel->session->session_state ==
      SSH_SESSION_STATE_ERROR)
    return SSH_ERROR;
  return channel->exit_status;
}

/*
 * This function acts as a meta select.
 *
 * First, channels are analyzed to seek potential can-write or can-read ones,
 * then if no channel has been elected, it goes in a loop with the posix
 * select(2).
 * This is made in two parts: protocol select and network select. The protocol
 * select does not use the network functions at all
 */
static int channel_protocol_select(ssh_channel *rchans, ssh_channel *wchans,
    ssh_channel *echans, ssh_channel *rout, ssh_channel *wout, ssh_channel *eout) {
  ssh_channel chan;
  int i;
  int j = 0;

  for (i = 0; rchans[i] != NULL; i++) {
    chan = rchans[i];

    while (ssh_channel_is_open(chan) && ssh_socket_data_available(chan->session->socket)) {
      ssh_handle_packets(chan->session, SSH_TIMEOUT_NONBLOCKING);
    }

    if ((chan->stdout_buffer && buffer_get_rest_len(chan->stdout_buffer) > 0) ||
        (chan->stderr_buffer && buffer_get_rest_len(chan->stderr_buffer) > 0) ||
        chan->remote_eof) {
      rout[j] = chan;
      j++;
    }
  }
  rout[j] = NULL;

  j = 0;
  for(i = 0; wchans[i] != NULL; i++) {
    chan = wchans[i];
    /* It's not our business to seek if the file descriptor is writable */
    if (ssh_socket_data_writable(chan->session->socket) &&
        ssh_channel_is_open(chan) && (chan->remote_window > 0)) {
      wout[j] = chan;
      j++;
    }
  }
  wout[j] = NULL;

  j = 0;
  for (i = 0; echans[i] != NULL; i++) {
    chan = echans[i];

    if (!ssh_socket_is_open(chan->session->socket) || ssh_channel_is_closed(chan)) {
      eout[j] = chan;
      j++;
    }
  }
  eout[j] = NULL;

  return 0;
}

/* Just count number of pointers in the array */
static int count_ptrs(ssh_channel *ptrs) {
  int c;
  for (c = 0; ptrs[c] != NULL; c++)
    ;

  return c;
}

/**
 * @brief Act like the standard select(2) on channels.
 *
 * The list of pointers are then actualized and will only contain pointers to
 * channels that are respectively readable, writable or have an exception to
 * trap.
 *
 * @param[in]  readchans A NULL pointer or an array of channel pointers,
 *                       terminated by a NULL.
 *
 * @param[in]  writechans A NULL pointer or an array of channel pointers,
 *                        terminated by a NULL.
 *
 * @param[in]  exceptchans A NULL pointer or an array of channel pointers,
 *                         terminated by a NULL.
 *
 * @param[in]  timeout  Timeout as defined by select(2).
 *
 * @return             SSH_OK on a successful operation, SSH_EINTR if the
 *                     select(2) syscall was interrupted, then relaunch the
 *                     function.
 */
int ssh_channel_select(ssh_channel *readchans, ssh_channel *writechans,
    ssh_channel *exceptchans, struct timeval * timeout) {
  ssh_channel *rchans, *wchans, *echans;
  ssh_channel dummy = NULL;
  ssh_event event = NULL;
  int rc;
  int i;
  int tm, tm_base;
  int firstround=1;
  struct ssh_timestamp ts;

  if (timeout != NULL)
    tm_base = timeout->tv_sec * 1000 + timeout->tv_usec/1000;
  else
    tm_base = SSH_TIMEOUT_INFINITE;
  ssh_timestamp_init(&ts);
  tm = tm_base;
  /* don't allow NULL pointers */
  if (readchans == NULL) {
    readchans = &dummy;
  }

  if (writechans == NULL) {
    writechans = &dummy;
  }

  if (exceptchans == NULL) {
    exceptchans = &dummy;
  }

  if (readchans[0] == NULL && writechans[0] == NULL && exceptchans[0] == NULL) {
    /* No channel to poll?? Go away! */
    return 0;
  }

  /* Prepare the outgoing temporary arrays */
  rchans = malloc(sizeof(ssh_channel ) * (count_ptrs(readchans) + 1));
  if (rchans == NULL) {
    return SSH_ERROR;
  }

  wchans = malloc(sizeof(ssh_channel ) * (count_ptrs(writechans) + 1));
  if (wchans == NULL) {
    SAFE_FREE(rchans);
    return SSH_ERROR;
  }

  echans = malloc(sizeof(ssh_channel ) * (count_ptrs(exceptchans) + 1));
  if (echans == NULL) {
    SAFE_FREE(rchans);
    SAFE_FREE(wchans);
    return SSH_ERROR;
  }

  /*
   * First, try without doing network stuff then, use the ssh_poll
   * infrastructure to poll on all sessions.
   */
  do {
    channel_protocol_select(readchans, writechans, exceptchans,
        rchans, wchans, echans);
    if (rchans[0] != NULL || wchans[0] != NULL || echans[0] != NULL) {
      /* At least one channel has an event */
      break;
    }
    /* Add all channels' sessions right into an event object */
    if (event == NULL) {
      event = ssh_event_new();
      if (event == NULL) {
          SAFE_FREE(rchans);
          SAFE_FREE(wchans);
          SAFE_FREE(echans);

          return SSH_ERROR;
      }
      for (i = 0; readchans[i] != NULL; i++) {
        ssh_poll_get_default_ctx(readchans[i]->session);
        ssh_event_add_session(event, readchans[i]->session);
      }
      for (i = 0; writechans[i] != NULL; i++) {
        ssh_poll_get_default_ctx(writechans[i]->session);
        ssh_event_add_session(event, writechans[i]->session);
      }
      for (i = 0; exceptchans[i] != NULL; i++) {
        ssh_poll_get_default_ctx(exceptchans[i]->session);
        ssh_event_add_session(event, exceptchans[i]->session);
      }
    }
    /* Get out if the timeout has elapsed */
    if (!firstround && ssh_timeout_elapsed(&ts, tm_base)){
      break;
    }
    /* Here we go */
    rc = ssh_event_dopoll(event,tm);
    if (rc != SSH_OK){
      SAFE_FREE(rchans);
      SAFE_FREE(wchans);
      SAFE_FREE(echans);
      ssh_event_free(event);
      return rc;
    }
    tm = ssh_timeout_update(&ts, tm_base);
    firstround=0;
  } while(1);

  memcpy(readchans, rchans, (count_ptrs(rchans) + 1) * sizeof(ssh_channel ));
  memcpy(writechans, wchans, (count_ptrs(wchans) + 1) * sizeof(ssh_channel ));
  memcpy(exceptchans, echans, (count_ptrs(echans) + 1) * sizeof(ssh_channel ));
  SAFE_FREE(rchans);
  SAFE_FREE(wchans);
  SAFE_FREE(echans);
  if(event)
    ssh_event_free(event);
  return 0;
}

/**
 * @brief Set the channel data counter.
 *
 * @code
 * struct ssh_counter_struct counter = {
 *     .in_bytes = 0,
 *     .out_bytes = 0,
 *     .in_packets = 0,
 *     .out_packets = 0
 * };
 *
 * ssh_channel_set_counter(channel, &counter);
 * @endcode
 *
 * @param[in] channel The SSH channel.
 *
 * @param[in] counter Counter for bytes handled by the channel.
 */
void ssh_channel_set_counter(ssh_channel channel,
                             ssh_counter counter) {
    if (channel != NULL) {
        channel->counter = counter;
    }
}

#if WITH_SERVER
/**
 * @brief Blocking write on a channel stderr.
 *
 * @param[in]  channel  The channel to write to.
 *
 * @param[in]  data     A pointer to the data to write.
 *
 * @param[in]  len      The length of the buffer to write to.
 *
 * @return              The number of bytes written, SSH_ERROR on error.
 *
 * @see ssh_channel_read()
 */
int ssh_channel_write_stderr(ssh_channel channel, const void *data, uint32_t len) {
  return channel_write_common(channel, data, len, 1);
}

/**
 * @brief Open a TCP/IP reverse forwarding channel.
 *
 * @param[in]  channel  An allocated channel.
 *
 * @param[in]  remotehost The remote host to connected (host name or IP).
 *
 * @param[in]  remoteport The remote port.
 *
 * @param[in]  sourcehost The source host (your local computer). It's optional
 *                        and for logging purpose.
 *
 * @param[in]  localport  The source port (your local computer). It's optional
 *                        and for logging purpose.
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 *
 * @warning This function does not bind the local port and does not automatically
 *          forward the content of a socket to the channel. You still have to
 *          use channel_read and channel_write for this.
 */
int ssh_channel_open_reverse_forward(ssh_channel channel, const char *remotehost,
    int remoteport, const char *sourcehost, int localport) {
  ssh_session session;
  ssh_buffer payload = NULL;
  int rc = SSH_ERROR;

  if(channel == NULL) {
      return rc;
  }
  if(remotehost == NULL || sourcehost == NULL) {
      ssh_set_error_invalid(channel->session);
      return rc;
  }

  session = channel->session;

  if(channel->state != SSH_CHANNEL_STATE_NOT_OPEN)
    goto pending;
  payload = ssh_buffer_new();
  if (payload == NULL) {
    ssh_set_error_oom(session);
    goto error;
  }
  rc = ssh_buffer_pack(payload,
                       "sdsd",
                       remotehost,
                       remoteport,
                       sourcehost,
                       localport);
  if (rc != SSH_OK){
    ssh_set_error_oom(session);
    goto error;
  }
pending:
  rc = channel_open(channel,
                    "forwarded-tcpip",
                    CHANNEL_INITIAL_WINDOW,
                    CHANNEL_MAX_PACKET,
                    payload);

error:
  ssh_buffer_free(payload);

  return rc;
}

/**
 * @brief Open a X11 channel.
 *
 * @param[in]  channel      An allocated channel.
 *
 * @param[in]  orig_addr    The source host (the local server).
 *
 * @param[in]  orig_port    The source port (the local server).
 *
 * @return              SSH_OK on success,
 *                      SSH_ERROR if an error occurred,
 *                      SSH_AGAIN if in nonblocking mode and call has
 *                      to be done again.
 * @warning This function does not bind the local port and does not automatically
 *          forward the content of a socket to the channel. You still have to
 *          use channel_read and channel_write for this.
 */
int ssh_channel_open_x11(ssh_channel channel, 
        const char *orig_addr, int orig_port) {
  ssh_session session;
  ssh_buffer payload = NULL;
  int rc = SSH_ERROR;

  if(channel == NULL) {
      return rc;
  }
  if(orig_addr == NULL) {
      ssh_set_error_invalid(channel->session);
      return rc;
  }
  session = channel->session;

  if(channel->state != SSH_CHANNEL_STATE_NOT_OPEN)
    goto pending;

  payload = ssh_buffer_new();
  if (payload == NULL) {
    ssh_set_error_oom(session);
    goto error;
  }

  rc = ssh_buffer_pack(payload,
                       "sd",
                       orig_addr,
                       orig_port);
  if (rc != SSH_OK) {
    ssh_set_error_oom(session);
    goto error;
  }
pending:
  rc = channel_open(channel,
                    "x11",
                    CHANNEL_INITIAL_WINDOW,
                    CHANNEL_MAX_PACKET,
                    payload);

error:
  ssh_buffer_free(payload);

  return rc;
}

/**
 * @brief Send the exit status to the remote process
 *
 * Sends the exit status to the remote process (as described in RFC 4254,
 * section 6.10).
 * Only SSH-v2 is supported (I'm not sure about SSH-v1).
 *
 * @param[in]  channel  The channel to send exit status.
 *
 * @param[in]  exit_status  The exit status to send
 *
 * @return     SSH_OK on success, SSH_ERROR if an error occurred.
 *             (including attempts to send exit status via SSH-v1 session).
 */
int ssh_channel_request_send_exit_status(ssh_channel channel, int exit_status) {
  ssh_buffer buffer = NULL;
  int rc = SSH_ERROR;

  if(channel == NULL) {
      return SSH_ERROR;
  }

#ifdef WITH_SSH1
  if (channel->version == 1) {
    return SSH_ERROR; // TODO: Add support for SSH-v1 if possible.
  }
#endif

  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    ssh_set_error_oom(channel->session);
    goto error;
  }

  rc = ssh_buffer_pack(buffer, "d", exit_status);
  if (rc != SSH_OK) {
    ssh_set_error_oom(channel->session);
    goto error;
  }

  rc = channel_request(channel, "exit-status", buffer, 0);
error:
  ssh_buffer_free(buffer);
  return rc;
}

/**
 * @brief Send an exit signal to remote process (RFC 4254, section 6.10).
 *
 * This sends the exit status of the remote process.
 * Note, that remote system may not support signals concept.
 * In such a case this request will be silently ignored.
 * Only SSH-v2 is supported (I'm not sure about SSH-v1).
 *
 * @param[in]  channel  The channel to send signal.
 *
 * @param[in]  sig      The signal to send (without SIG prefix)
 *                      (e.g. "TERM" or "KILL").
 * @param[in]  core     A boolean to tell if a core was dumped
 * @param[in]  errmsg   A CRLF explanation text about the error condition
 * @param[in]  lang     The language used in the message (format: RFC 3066)
 *
 * @return              SSH_OK on success, SSH_ERROR if an error occurred
 *                      (including attempts to send signal via SSH-v1 session).
 */
int ssh_channel_request_send_exit_signal(ssh_channel channel, const char *sig,
                            int core, const char *errmsg, const char *lang) {
  ssh_buffer buffer = NULL;
  int rc = SSH_ERROR;

  if(channel == NULL) {
      return rc;
  }
  if(sig == NULL || errmsg == NULL || lang == NULL) {
      ssh_set_error_invalid(channel->session);
      return rc;
  }
#ifdef WITH_SSH1
  if (channel->version == 1) {
    return SSH_ERROR; // TODO: Add support for SSH-v1 if possible.
  }
#endif

  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    ssh_set_error_oom(channel->session);
    goto error;
  }

  rc = ssh_buffer_pack(buffer,
                       "sbss",
                       sig,
                       core ? 1 : 0,
                       errmsg,
                       lang);
  if (rc != SSH_OK) {
    ssh_set_error_oom(channel->session);
    goto error;
  }

  rc = channel_request(channel, "exit-signal", buffer, 0);
error:
  ssh_buffer_free(buffer);
  return rc;
}

#endif

/* @} */

/* vim: set ts=4 sw=4 et cindent: */