1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
|
/*
(c) Copyright 2012 - 2018 Anton Sviridenko
https://picapica.im
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "PICA_security.h"
#include "PICA_client.h"
#include "PICA_media.h"
#include "PICA_proto.h"
#include "PICA_msgproc.h"
#include "PICA_common.h"
#include "PICA_signverify.h"
#include "PICA_netconf.h"
#include <openssl/dh.h>
#include <string.h>
#include <time.h>
#define PICA_DEBUG
#ifdef PICA_DEBUG
#define PICA_TRACEFUNC fprintf(stderr, "%s()\n", __PRETTY_FUNCTION__);
#else
#define PICA_TRACEFUNC
#endif
static struct PICA_client_callbacks callbacks;
#ifdef PICA_MULTITHREADED
#ifdef WIN32
static HANDLE *mt_locks;
const char *PICA_inet_ntop(int af, const void *src, char *dst, size_t size);
/* own implementation of inet_ntop() for WinXP compatibility */
#define inet_ntop PICA_inet_ntop
#else
static pthread_mutex_t *mt_locks;
#endif
#endif
static int PICA_send_file_fragment(struct PICA_c2c *chn);
static int PICA_sendfile_open_read(struct PICA_c2c *chn, const char *filename_utf8, uint64_t *file_size);
static int PICA_recvfile_open_write(struct PICA_c2c *chn, const char *filename_utf8, unsigned int filenamesize);
static int PICA_send_filecontrol(struct PICA_c2c *chan, int senderctl, int receiverctl);
static int PICA_send_directc2caddrlist(struct PICA_c2c *chn);
static int PICA_send_directc2cfailed(struct PICA_c2c *chn);
static int PICA_send_directc2c_switch(struct PICA_c2c *chn);
static unsigned int procmsg_INITRESP(unsigned char*, unsigned int, void*);
static unsigned int procmsg_CONNREQINC(unsigned char*, unsigned int, void*);
static unsigned int procmsg_NOTFOUND(unsigned char*, unsigned int, void*);
static unsigned int procmsg_FOUND(unsigned char*, unsigned int, void*);
static unsigned int procmsg_CLNODELIST(unsigned char*, unsigned int, void*);
static unsigned int procmsg_MSGUTF8(unsigned char*, unsigned int, void*);
static unsigned int procmsg_MSGOK(unsigned char*, unsigned int, void*);
static unsigned int procmsg_PINGREQ(unsigned char*, unsigned int, void*);
static unsigned int procmsg_SENDFILEREQUEST(unsigned char*, unsigned int, void*);
static unsigned int procmsg_ACCEPTEDFILE(unsigned char*, unsigned int, void*);
static unsigned int procmsg_DENIEDFILE(unsigned char*, unsigned int, void*);
static unsigned int procmsg_FILEFRAGMENT(unsigned char*, unsigned int, void*);
static unsigned int procmsg_FILECONTROL(unsigned char*, unsigned int, void*);
static unsigned int procmsg_INITRESP_c2c(unsigned char*, unsigned int, void*);
static unsigned int procmsg_C2CCONNREQ(unsigned char*, unsigned int, void*);
static unsigned int procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST(unsigned char*, unsigned int, void*);
static unsigned int procmsg_PICA_PROTO_DIRECTC2C_FAILED(unsigned char*, unsigned int, void*);
static unsigned int procmsg_PICA_PROTO_DIRECTC2C_SWITCH(unsigned char*, unsigned int, void*);
static unsigned int procmsg_MULTILOGIN(unsigned char*, unsigned int, void*);
static unsigned int procmsg_CALLREQ(unsigned char*, unsigned int, void*);
static unsigned int procmsg_CALLANS(unsigned char*, unsigned int, void*);
static unsigned int procmsg_CALLREJ(unsigned char*, unsigned int, void*);
static unsigned int procmsg_CALLFIN(unsigned char*, unsigned int, void*);
static unsigned int procmsg_CALL_AUDIOPARAM(unsigned char*, unsigned int, void*);
static unsigned int procmsg_CALL_VIDEOPARAM(unsigned char*, unsigned int, void*);
static unsigned int procmsg_CALL_AUDIO_PACKET(unsigned char*, unsigned int, void*);
static unsigned int procmsg_CALL_VIDEO_PACKET(unsigned char*, unsigned int, void*);
static unsigned int procmsg_CALL_RECEPTION_REPORT(unsigned char*, unsigned int, void*);
static unsigned int procmsg_MEDIA_PINGREQ(unsigned char*, unsigned int, void*);
static unsigned int procmsg_MEDIA_PINGREP(unsigned char*, unsigned int, void*);
static unsigned int procmsg_MYTCPADDR(unsigned char*, unsigned int, void*);
static unsigned int procmsg_MYUDPADDRTOKEN(unsigned char*, unsigned int, void*);
static unsigned int procmsg_MYUDPADDR(unsigned char*, unsigned int, void*);
static struct PICA_proto_msg* c2n_writebuf_push(struct PICA_c2n *ci, unsigned int msgid, unsigned int size);
static struct PICA_proto_msg* c2c_writebuf_push(struct PICA_c2c *chn, unsigned int msgid, unsigned int size);
static int process_first_async_connect_result(int connect_ret);
static int check_async_connect_result(int sock, struct sockaddr* a, int addrlen);
static int process_async_ssl_errors(SSL *ssl, int ret, int *want_write, int *want_read);
static int PICA_write_c2n(struct PICA_c2n *ci);
static int PICA_write_c2c(struct PICA_c2c *chn);
static int PICA_write_ssl(SSL *ssl, unsigned char *buf, unsigned int *ppos, unsigned int *btw);
static int PICA_read_c2n(struct PICA_c2n *ci);
static int PICA_read_c2c(struct PICA_c2c *chn);
static int PICA_read_ssl(SSL *ssl, unsigned char *buf, unsigned int *ppos, unsigned int size);
#define MSGINFO_MSGSNUM(arr) (sizeof(arr)/sizeof(struct PICA_msginfo))
const struct PICA_msginfo c2n_messages[] =
{
{PICA_PROTO_CONNREQINC, PICA_MSG_FIXED_SIZE, PICA_PROTO_CONNREQINC_SIZE, procmsg_CONNREQINC},
{PICA_PROTO_NOTFOUND, PICA_MSG_FIXED_SIZE, PICA_PROTO_NOTFOUND_SIZE, procmsg_NOTFOUND},
{PICA_PROTO_FOUND, PICA_MSG_FIXED_SIZE, PICA_PROTO_FOUND_SIZE, procmsg_FOUND},
{PICA_PROTO_CLNODELIST, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CLNODELIST},
{PICA_PROTO_PINGREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREQ_SIZE, procmsg_PINGREQ},
{PICA_PROTO_INITRESPOK, PICA_MSG_FIXED_SIZE, PICA_PROTO_INITRESPOK_SIZE, procmsg_INITRESP},
{PICA_PROTO_VERDIFFER, PICA_MSG_FIXED_SIZE, PICA_PROTO_VERDIFFER_SIZE, procmsg_INITRESP},
{PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN},
{PICA_PROTO_MYTCPADDR_IPV4, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYTCPADDR_IPV4_SIZE, procmsg_MYTCPADDR},
{PICA_PROTO_MYTCPADDR_IPV6, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYTCPADDR_IPV6_SIZE, procmsg_MYTCPADDR},
{PICA_PROTO_MYUDPADDRTOKEN, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYUDPADDRTOKEN_SIZE, procmsg_MYUDPADDRTOKEN},
{PICA_PROTO_MYUDPADDR, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT8, procmsg_MYUDPADDR}
};
const struct PICA_msginfo c2c_messages[] =
{
{PICA_PROTO_MSGUTF8, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MSGUTF8},
{PICA_PROTO_MSGOK, PICA_MSG_FIXED_SIZE, PICA_PROTO_MSGOK_SIZE, procmsg_MSGOK},
{PICA_PROTO_CALLREQ, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALLREQ},
{PICA_PROTO_CALLANS, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALLANS},
{PICA_PROTO_CALLREJ, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALLREJ_SIZE, procmsg_CALLREJ},
{PICA_PROTO_CALLFIN, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALLFIN_SIZE, procmsg_CALLFIN},
{PICA_PROTO_CALL_AUDIOPARAM, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALL_AUDIOPARAM_SIZE, procmsg_CALL_AUDIOPARAM},
{PICA_PROTO_CALL_VIDEOPARAM, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALL_VIDEOPARAM_SIZE, procmsg_CALL_VIDEOPARAM},
{PICA_PROTO_CALL_AUDIO_PACKET, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALL_AUDIO_PACKET},
{PICA_PROTO_CALL_VIDEO_PACKET, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALL_VIDEO_PACKET},
{PICA_PROTO_CALL_RECEPTION_REPORT, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALL_RECEPTION_REPORT_SIZE, procmsg_CALL_RECEPTION_REPORT},
{PICA_PROTO_SENDFILEREQUEST, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_SENDFILEREQUEST},
{PICA_PROTO_ACCEPTEDFILE, PICA_MSG_FIXED_SIZE, PICA_PROTO_ACCEPTEDFILE_SIZE, procmsg_ACCEPTEDFILE},
{PICA_PROTO_DENIEDFILE, PICA_MSG_FIXED_SIZE, PICA_PROTO_DENIEDFILE_SIZE, procmsg_DENIEDFILE},
{PICA_PROTO_FILEFRAGMENT, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_FILEFRAGMENT},
{PICA_PROTO_FILECONTROL, PICA_MSG_FIXED_SIZE, PICA_PROTO_FILECONTROL_SIZE, procmsg_FILECONTROL},
{PICA_PROTO_DIRECTC2C_ADDRLIST, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST},
{PICA_PROTO_DIRECTC2C_FAILED, PICA_MSG_FIXED_SIZE, PICA_PROTO_DIRECTC2C_FAILED_SIZE, procmsg_PICA_PROTO_DIRECTC2C_FAILED},
{PICA_PROTO_DIRECTC2C_SWITCH, PICA_MSG_FIXED_SIZE, PICA_PROTO_DIRECTC2C_SWITCH_SIZE, procmsg_PICA_PROTO_DIRECTC2C_SWITCH},
{PICA_PROTO_C2CCONNREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_C2CCONNREQ_SIZE, procmsg_C2CCONNREQ},
{PICA_PROTO_INITRESPOK, PICA_MSG_FIXED_SIZE, PICA_PROTO_INITRESPOK_SIZE, procmsg_INITRESP_c2c},
{PICA_PROTO_VERDIFFER, PICA_MSG_FIXED_SIZE, PICA_PROTO_VERDIFFER_SIZE, procmsg_INITRESP_c2c}
};
struct PICA_msginfo c2c_init_messages[] =
{
};
/* What a datagram of a mediac2c connection can carry, see PICA_media.h */
const struct PICA_msginfo media_messages[] =
{
{PICA_PROTO_CALL_AUDIO_PACKET, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALL_AUDIO_PACKET},
{PICA_PROTO_CALL_VIDEO_PACKET, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALL_VIDEO_PACKET},
{PICA_PROTO_PINGREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREQ_SIZE, procmsg_MEDIA_PINGREQ},
{PICA_PROTO_PINGREP, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREP_SIZE, procmsg_MEDIA_PINGREP}
};
unsigned int PICA_media_process_messages(unsigned char *buf, unsigned int *read_pos, struct PICA_c2c *c2c)
{
return PICA_processdatastream(buf, read_pos, c2c, media_messages, MSGINFO_MSGSNUM(media_messages));
}
void PICA_media_transport_changed(struct PICA_c2c *c2c, int transport, const char *ciphersuitename)
{
if (callbacks.call_media_transport_cb)
callbacks.call_media_transport_cb(c2c->peer_id, transport, ciphersuitename,
PICA_media_max_payload(c2c));
}
int PICA_media_send_ping(struct PICA_c2c *c2c, int reply)
{
unsigned char buf[PICA_PROTO_PINGREQ_SIZE];
buf[0] = buf[1] = reply ? PICA_PROTO_PINGREP : PICA_PROTO_PINGREQ;
RAND_pseudo_bytes(buf + 2, 2);
return PICA_media_send(c2c, buf, sizeof(buf));
}
static unsigned int procmsg_MEDIA_PINGREQ(unsigned char* buf, unsigned int nb, void* p)
{
PICA_media_send_ping((struct PICA_c2c *)p, 1);
return 1;
}
static unsigned int procmsg_MEDIA_PINGREP(unsigned char* buf, unsigned int nb, void* p)
{
/* Nothing to do: a ping reply is only interesting as a sign that the
* connection still works, and receiving it already updated the time the
* last datagram arrived at.
*/
return 1;
}
int PICA_get_id_from_cert_file(const char *cert_file, unsigned char *id)
{
X509 *x;
FILE *f;
int ret;
f = fopen(cert_file, "r");
if (!f)
{
perror(cert_file);
return 0;
}
x = PEM_read_X509(f, 0, 0, 0);
fclose(f);
if (!x)
{
return 0;
}
ret = PICA_id_from_X509(x, id);
X509_free(x);
return ret;
}
int PICA_get_id_from_cert_string(const char *cert_pem, unsigned char *id)
{
X509 *x;
BIO *biomem;
biomem = BIO_new_mem_buf(cert_pem, -1);
x = PEM_read_bio_X509(biomem, NULL, 0, NULL);
if (!x)
{
return 0;
}
return PICA_id_from_X509(x, id);
}
int PICA_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
{
//return 1 for self-signed certificates
char buf[256];
X509 *err_cert;
int err, depth;
err_cert = X509_STORE_CTX_get_current_cert(ctx);
err = X509_STORE_CTX_get_error(ctx);
depth = X509_STORE_CTX_get_error_depth(ctx);
X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && depth == 0)
preverify_ok = 1;
if (!preverify_ok)
{
printf("verify error:num=%d:%s:depth=%d:%s\n", err,
X509_verify_cert_error_string(err), depth, buf);
}
return preverify_ok;
}
static int c2n_alloc_c2c(struct PICA_c2n *ci, struct PICA_c2c **chn, const unsigned char *peer_id, int is_outgoing)
{
struct PICA_c2c *chnl;
chnl = *chn = (struct PICA_c2c*)calloc(sizeof(struct PICA_c2c), 1);
if (!chnl)
return 0;//ERR_CHECK
chnl->conn = ci;
chnl->outgoing = is_outgoing;
chnl->directc2c_config = ci->directc2c_config;
memcpy(chnl->peer_id, peer_id, PICA_ID_SIZE);
chnl->acc = ci->acc;
chnl->timestamp = time(0);
chnl->sck_data = -1;//prevent closing stdin when closing non-active connection
chnl->read_buf = calloc(PICA_CHANREADBUFSIZE, 1);
if (ci->chan_list_head)
{
ci->chan_list_end->next = chnl;
chnl->prev = ci->chan_list_end;
ci->chan_list_end = chnl;
}
else
{
ci->chan_list_head = chnl;
ci->chan_list_end = chnl;
}
chnl->state = PICA_C2C_STATE_NEW;
chnl->directc2c_state = PICA_DIRECTC2C_STATE_INACTIVE;
return 1;
}
static int c2c_stage2_startanontls(struct PICA_c2c *chnl)
{
int ret;
PICA_TRACEFUNC
chnl->ssl = SSL_new(chnl->acc->anon_ctx);
if (!chnl->ssl)
return PICA_ERRSSL;
ret = SSL_set_fd(chnl->ssl, chnl->sck_data);
if (ret != 1)
return PICA_ERRSSL;
ret = SSL_connect(chnl->ssl);
ret = process_async_ssl_errors(chnl->ssl, ret, &chnl->want_write, 0);
if (ret != PICA_OK)
return ret;
chnl->state = PICA_C2C_STATE_WAITINGANONTLS;
return PICA_OK;
}
static int c2c_stage3_connid(struct PICA_c2c *chnl)
{
struct PICA_proto_msg *mp;
mp = c2c_writebuf_push(chnl, PICA_PROTO_CONNID, PICA_PROTO_CONNID_SIZE);
if (mp)
{
if (chnl->outgoing)
{
memcpy(mp->tail, chnl->acc->id, PICA_ID_SIZE);/* caller ID*/
memcpy(mp->tail + PICA_ID_SIZE, chnl->peer_id, PICA_ID_SIZE);/* callee ID*/
}
else
{
memcpy(mp->tail, chnl->peer_id, PICA_ID_SIZE);/* caller ID*/
memcpy(mp->tail + PICA_ID_SIZE, chnl->acc->id, PICA_ID_SIZE);/* callee ID*/
}
chnl->state = PICA_C2C_STATE_CONNID;
}
else
{
return PICA_ERRNOMEM;
}
return PICA_OK;
}
static int c2c_stage4_shutdownanontls(struct PICA_c2c *chnl)
{
int ret;
ret = SSL_shutdown(chnl->ssl);
if (ret < 0)
ret = process_async_ssl_errors(chnl->ssl, ret, &chnl->want_write, 0);
if (ret != PICA_OK)
return ret;
chnl->state = PICA_C2C_STATE_WAITINGANONTLSSHUTDOWN;
return PICA_OK;
}
static int c2c_stage5_starttls(struct PICA_c2c *chnl)
{
int ret;
SSL_free(chnl->ssl);
chnl->ssl = SSL_new(chnl->acc->ctx);
if (!chnl->ssl)
{
return PICA_ERRSSL;
}
ret = SSL_set_fd(chnl->ssl, chnl->sck_data);
if (!ret)
{
return PICA_ERRSSL;
}
SSL_set_verify(chnl->ssl, SSL_VERIFY_PEER, PICA_verify_callback);
SSL_set_verify_depth(chnl->ssl, 1);//peer certificate and one CA
if (chnl->outgoing)
ret = SSL_connect(chnl->ssl);
else
ret = SSL_accept(chnl->ssl);
if (ret == 0)
return PICA_ERRSSL;
if (ret < 0)
{
ret = SSL_get_error(chnl->ssl, ret);
if (ret != SSL_ERROR_WANT_READ && ret != SSL_ERROR_WANT_WRITE)
return PICA_ERRSSL;
}
chnl->state = PICA_C2C_STATE_WAITINGTLS;
return PICA_OK;
}
int PICA_verify_peer_cert_common(X509 **peer_cert, SSL *ssl, const unsigned char *peer_id)
{
unsigned char idbuf[PICA_ID_SIZE];
EVP_PKEY *pubkey;
RSA *rsa;
*peer_cert = SSL_get_peer_certificate(ssl);
if (!*peer_cert)
return PICA_ERRNOPEERCERT;
pubkey = X509_get_pubkey(*peer_cert);
if (!pubkey)
return PICA_ERRNOPEERCERT;
rsa = EVP_PKEY_get1_RSA(pubkey);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
if (!rsa || !rsa->n || BN_num_bits(rsa->n) < PICA_RSA_MINKEYSIZE)
#else
if (!rsa || RSA_bits(rsa) < PICA_RSA_MINKEYSIZE)
#endif
return PICA_ERRNOPEERCERT;
RSA_free(rsa);
EVP_PKEY_free(pubkey);
if (PICA_id_from_X509(*peer_cert, idbuf) == 0)
{
return PICA_ERRNOPEERCERT;
}
if (memcmp(idbuf, peer_id, PICA_ID_SIZE) != 0)
{
return PICA_ERRINVPEERCERT;
}
{
BIO *mem = BIO_new(BIO_s_mem());
char *cert_pem;
unsigned int cert_pem_nb;
PEM_write_bio_X509(mem, *peer_cert);
cert_pem_nb = (unsigned int)BIO_get_mem_data(mem, &cert_pem);
if (callbacks.peer_cert_verify_cb(peer_id, (const char*)cert_pem, cert_pem_nb) == 0)
{
BIO_free(mem);
return PICA_ERRINVPEERCERT;
}
BIO_free(mem);
}
return PICA_OK;
}
static int c2c_verify_peer_cert(struct PICA_c2c *chnl)
{
return PICA_verify_peer_cert_common(&chnl->peer_cert, chnl->ssl, chnl->peer_id);
}
static int c2c_stage6_sendc2cconnreq(struct PICA_c2c *chnl)
{
struct PICA_proto_msg *mp;
mp = c2c_writebuf_push(chnl, PICA_PROTO_C2CCONNREQ, PICA_PROTO_C2CCONNREQ_SIZE);
if (!mp)
return PICA_ERRNOMEM;
mp->tail[0] = PICA_C2CPROTO_VER_HIGH;
mp->tail[1] = PICA_C2CPROTO_VER_LOW;
chnl->state = PICA_C2C_STATE_WAITINGREP;
return PICA_OK;
}
static int c2c_start(struct PICA_c2c *chnl)
{
int ret, err_ret;
/* Defensive: c2c_start() opens a new socket and resets the channel to
* CONNECTING without touching chnl->ssl or the write buffer. Running it
* on a channel that is past NEW would strand the existing session and
* reroute buffered data, so refuse unless the channel is still new.
*/
if (chnl->state != PICA_C2C_STATE_NEW)
return PICA_ERRINVARG;
chnl->sck_data = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
IOCTLSETNONBLOCKINGSOCKET(chnl->sck_data, 1);
SETTCPNODELAY(chnl->sck_data);
{
struct sockaddr_in addr = chnl->conn->srv_addr;
addr.sin_port = htons(ntohs(addr.sin_port));
chnl->state = PICA_C2C_STATE_CONNECTING;
ret = connect(chnl->sck_data, (struct sockaddr*)&addr, sizeof(struct sockaddr_in));
if (ret == 0)
{
ret = c2c_stage2_startanontls(chnl);
if (ret != PICA_OK)
{
err_ret = ret;
goto error_ret;
}
return PICA_OK;
}
if ((err_ret = process_first_async_connect_result(ret)) != PICA_OK)
goto error_ret;
}
return PICA_OK;
error_ret:
callbacks.c2c_failed_cb(chnl->peer_id);
PICA_close_c2c(chnl);
return err_ret;
}
static unsigned int procmsg_C2CCONNREQ(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2c *cc = (struct PICA_c2c *)p;
struct PICA_proto_msg *mp;
if (cc->state != PICA_C2C_STATE_WAITINGC2CPROTOVER)
return 0;
if (buf[2] == PICA_C2CPROTO_VER_HIGH && buf[3] == PICA_C2CPROTO_VER_LOW)
{
//send ok
mp = c2c_writebuf_push(cc, PICA_PROTO_INITRESPOK, PICA_PROTO_INITRESPOK_SIZE);
if (!mp)
return 0;
mp->tail[0] = 'O';
mp->tail[1] = 'K';
cc->state = PICA_C2C_STATE_ACTIVE;
callbacks.c2c_established_cb(cc->peer_id, SSL_get_cipher_name(cc->ssl));
if (cc->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING)
PICA_send_directc2caddrlist(cc);
}
else
{
//send verdiffer, disconnect after sending
mp = c2c_writebuf_push(cc, PICA_PROTO_VERDIFFER, PICA_PROTO_VERDIFFER_SIZE);
if (!mp)
return 0;
mp->tail[0] = PICA_C2CPROTO_VER_HIGH;
mp->tail[1] = PICA_C2CPROTO_VER_LOW;
cc->disconnect_on_empty_write_buf = 1;
}
return 1;
}
static unsigned int procmsg_INITRESP_c2c(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2c *cc = (struct PICA_c2c *)p;
if (cc->state != PICA_C2C_STATE_WAITINGREP)
return 0;
if (!cc->outgoing)
return 0;
switch(buf[0])
{
case PICA_PROTO_INITRESPOK:
cc->state = PICA_C2C_STATE_ACTIVE;
callbacks.c2c_established_cb(cc->peer_id, SSL_get_cipher_name(cc->ssl));
if (cc->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING)
PICA_send_directc2caddrlist(cc);
break;
case PICA_PROTO_VERDIFFER:
return 0; // -- ???
break;
default:
return 0;
}
return 1;
}
/* "address:port", for the log; buf has PICA_DIRECTC2C_ADDRSTRSIZE octets */
#define PICA_DIRECTC2C_ADDRSTRSIZE (INET6_ADDRSTRLEN + 6)
static const char *directc2c_addrstr(const struct sockaddr_in *a, char *buf)
{
char ip[INET6_ADDRSTRLEN];
if (!inet_ntop(AF_INET, &a->sin_addr, ip, sizeof(ip)))
strcpy(ip, "?");
sprintf(buf, "%s:%u", ip, (unsigned int)ntohs(a->sin_port));
return buf;
}
static int directc2c_connect_next(struct PICA_directc2c *dc2c, struct PICA_c2c *c2c)
{
PICA_TRACEFUNC
char addrstr[PICA_DIRECTC2C_ADDRSTRSIZE];
int ret;
if (dc2c->ssl)
SSL_free(dc2c->ssl);
dc2c->ssl = NULL;
if (dc2c->sck >= 0)
CLOSE(dc2c->sck);
dc2c->sck = -1;
/* the list holds IPv4 elements only, behind a length field in host byte
* order - see procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST()
*/
if (dc2c->addrpos == 0)
dc2c->addrpos += 2;
if (dc2c->addrpos + PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE > *(uint16_t*)dc2c->addrlist + 2)
{
fprintf(stderr, "directc2c: no more addresses to try\n");
return PICA_ERRNOTFOUND;
}
switch(dc2c->addrlist[dc2c->addrpos])
{
case PICA_PROTO_DIRECTC2C_IPV4:
dc2c->sck = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
IOCTLSETNONBLOCKINGSOCKET(dc2c->sck, 1);
SETTCPNODELAY(dc2c->sck);
memset(&dc2c->addr, 0, sizeof(dc2c->addr));
dc2c->addr.sin_family = AF_INET;
dc2c->addr.sin_addr.s_addr = *((in_addr_t*)(dc2c->addrlist + dc2c->addrpos + 1));
dc2c->addr.sin_port = *((uint16_t*)(dc2c->addrlist + dc2c->addrpos + 5));
/* the list only holds private addresses of a network this host is
* on, see directc2c_addrlist_ipv4() */
dc2c->attempt_started = PICA_media_now();
dc2c->attempt_deadline = dc2c->attempt_started
+ (PICA_is_private_addr_ipv4(dc2c->addr.sin_addr.s_addr)
? PICA_DIRECTC2C_LAN_CONNECT_TIMEOUT : PICA_DIRECTC2C_CONNECT_TIMEOUT);
fprintf(stderr, "directc2c: connecting to %s, timeout %u ms\n", directc2c_addrstr(&dc2c->addr, addrstr),
(unsigned int)(dc2c->attempt_deadline - dc2c->attempt_started));
dc2c->state = PICA_DIRECTC2C_CONNSTATE_CONNECTING;
ret = connect(dc2c->sck, (struct sockaddr*)&dc2c->addr, sizeof(dc2c->addr));
ret = process_first_async_connect_result(ret);
if (ret != PICA_OK)
{
fprintf(stderr, "directc2c: connection to %s failed\n", addrstr);
dc2c->state = PICA_DIRECTC2C_CONNSTATE_FAILED;
}
dc2c->addrpos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
break;
default:
return PICA_ERRNOTFOUND;
}
return PICA_OK;
}
/* Whether an IPv4 address of a received address list is worth connecting
* to. A private one is only if it is on a private network this host is on:
* anywhere else it is some other network's address, which leads nowhere or
* to the wrong host. Logs the decision.
*/
static int directc2c_addr_usable(const struct sockaddr_in *a, const in_addr_t *ifaddrs,
const in_addr_t *ifmasks, int ifcount)
{
char addrstr[PICA_DIRECTC2C_ADDRSTRSIZE];
char ifaddr[INET6_ADDRSTRLEN], ifmask[INET6_ADDRSTRLEN];
int i;
directc2c_addrstr(a, addrstr);
if (!PICA_is_private_addr_ipv4(a->sin_addr.s_addr))
{
fprintf(stderr, "directc2c: 0x0B address %s - public, will be tried\n", addrstr);
return 1;
}
if (ifcount == 0)
{
fprintf(stderr, "directc2c: 0x0B address %s - private, ignored: this host is on no private network\n", addrstr);
return 0;
}
i = PICA_find_subnet_ipv4(a->sin_addr.s_addr, ifaddrs, ifmasks, ifcount);
if (i < 0)
{
fprintf(stderr, "directc2c: 0x0B address %s - private, ignored: not on a private network of this host\n",
addrstr);
return 0;
}
if (!inet_ntop(AF_INET, &ifaddrs[i], ifaddr, sizeof(ifaddr)))
strcpy(ifaddr, "?");
if (!inet_ntop(AF_INET, &ifmasks[i], ifmask, sizeof(ifmask)))
strcpy(ifmask, "?");
fprintf(stderr, "directc2c: 0x0B address %s - private, on the network of local address %s netmask %s, will be tried\n",
addrstr, ifaddr, ifmask);
return 1;
}
/* Picks the IPv4 elements out of a received address list, in their order,
* into list, behind a length field in host byte order - those worth
* connecting to, see directc2c_addr_usable().
* Elements of the other types are stepped over by their size, see the 0xA4
* message. An element of an unknown type ends the list, as there is no
* knowing where it ends; so does a truncated one.
* \return size of what was written to list
*/
static unsigned int directc2c_addrlist_ipv4(const unsigned char *items, unsigned int len, uint8_t *list)
{
in_addr_t ifaddrs[PICA_IFADDRS_MAX], ifmasks[PICA_IFADDRS_MAX];
int ifcount;
unsigned int pos = 0;
uint16_t n = 0;
ifcount = PICA_get_private_ifaddrs_ipv4(ifaddrs, ifmasks, PICA_IFADDRS_MAX);
fprintf(stderr, "directc2c: received 0x0B, %u octets of addresses\n", len);
while (pos < len && n < PICA_DIRECTC2C_MAX_ADDRS)
{
switch (items[pos])
{
case PICA_PROTO_DIRECTC2C_IPV4:
{
struct sockaddr_in a;
if (pos + PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE > len)
{
fprintf(stderr, "directc2c: 0x0B truncated IPv4 address, end of list\n");
goto end;
}
memset(&a, 0, sizeof(a));
a.sin_family = AF_INET;
memcpy(&a.sin_addr.s_addr, items + pos + 1, 4);
memcpy(&a.sin_port, items + pos + 5, 2);
if (directc2c_addr_usable(&a, ifaddrs, ifmasks, ifcount))
{
memcpy(list + 2 + n * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE,
items + pos, PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE);
n++;
}
pos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
break;
}
case PICA_PROTO_DIRECTC2C_IPV6:
fprintf(stderr, "directc2c: 0x0B IPv6 address - ignored, not supported\n");
pos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV6_SIZE;
break;
case PICA_PROTO_DIRECTC2C_DNS:
if (pos + 1 >= len)
{
fprintf(stderr, "directc2c: 0x0B truncated DNS name, end of list\n");
goto end;
}
fprintf(stderr, "directc2c: 0x0B DNS name - ignored, not supported\n");
pos += 2 + items[pos + 1] + 2;
break;
default:
fprintf(stderr, "directc2c: 0x0B unknown address type 0x%02X, end of list\n", items[pos]);
goto end;
}
}
if (pos < len)
fprintf(stderr, "directc2c: 0x0B more than %i usable addresses, the rest is ignored\n", PICA_DIRECTC2C_MAX_ADDRS);
end:
*(uint16_t*)list = n * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
return 2 + n * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
}
static unsigned int procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST(unsigned char* buf, unsigned int nb, void* p)
{
PICA_TRACEFUNC
struct PICA_c2c *cc = (struct PICA_c2c *)p;
int ret;
if (cc->directc2c_config != PICA_DIRECTC2C_CFG_DISABLED)
{
if (cc->directc2c_state != PICA_DIRECTC2C_STATE_INACTIVE && cc->directc2c_state != PICA_DIRECTC2C_STATE_WAITINGINCOMING)
return 0;
/* the peer announces its addresses once */
if (cc->direct)
return 1;
if (cc->outgoing == PICA_C2C_OUTGOING || cc->directc2c_config == PICA_DIRECTC2C_CFG_CONNECTONLY)
cc->directc2c_state = PICA_DIRECTC2C_STATE_CONNECTING;
cc->direct = calloc(1, sizeof(struct PICA_directc2c));
if (!cc->direct)
return 1;
cc->direct->is_outgoing = PICA_DIRECTC2C_OUTGOING;
cc->direct->state = PICA_DIRECTC2C_CONNSTATE_NEW;
cc->direct->sck = -1;
cc->direct->addrlist = malloc(2 + PICA_DIRECTC2C_MAX_ADDRS * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE);
if (!cc->direct->addrlist)
return 1;
directc2c_addrlist_ipv4(buf + 4, nb - 4, cc->direct->addrlist);
cc->direct->addrpos = 0;
if (cc->outgoing == PICA_C2C_INCOMING && cc->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING)
return 1;//connect later, if no incoming connection is accepted and DIRECTC2C_FAILED is received
ret = directc2c_connect_next(cc->direct, cc);
if (ret == PICA_ERRNOTFOUND)
{
cc->directc2c_state = PICA_DIRECTC2C_STATE_FAILEDTOCONNECT;
}
}
return 1;
}
static unsigned int procmsg_PICA_PROTO_DIRECTC2C_FAILED(unsigned char* buf, unsigned int nb, void* p)
{
PICA_TRACEFUNC
struct PICA_c2c *cc = (struct PICA_c2c *)p;
int ret;
if (cc->directc2c_state != PICA_DIRECTC2C_STATE_WAITINGINCOMING)
return 0;
if (cc->directc2c_config == PICA_DIRECTC2C_CFG_DISABLED)
return 0;
if (cc->outgoing != PICA_C2C_INCOMING)
return 0;
/* FAILED tells us to connect to the peer instead, but we can only do
* that if the peer actually sent us its address list (which allocates
* cc->direct). Without it there is nothing to connect to.
*/
if (!cc->direct)
return 0;
ret = directc2c_connect_next(cc->direct, cc);
if (ret == PICA_ERRNOTFOUND)
cc->directc2c_state = PICA_DIRECTC2C_STATE_FAILEDTOCONNECT;
else
cc->directc2c_state = PICA_DIRECTC2C_STATE_CONNECTING;
return 1;
}
unsigned int procmsg_PICA_PROTO_DIRECTC2C_SWITCH(unsigned char* buf, unsigned int nb, void* p)
{
PICA_TRACEFUNC
struct PICA_c2c *cc = (struct PICA_c2c *)p;
int ret;
if (cc->directc2c_config == PICA_DIRECTC2C_CFG_DISABLED)
return 0;
if (cc->directc2c_state != PICA_DIRECTC2C_STATE_ACTIVE && cc->directc2c_state != PICA_DIRECTC2C_STATE_CONNECTING)
return 0;
/* A SWITCH may legitimately arrive while our own direct link is still
* CONNECTING, but switching reads to it before its SSL object exists
* would hand SSL_read() a NULL. Refuse until the direct session is there.
*/
if (!cc->direct || !cc->direct->ssl)
return 0;
cc->switched_to_directc2c_read = 1;
return 1;
}
static unsigned int procmsg_INITRESP(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2n *ci = (struct PICA_c2n *)p;
if (ci->state != PICA_C2N_STATE_WAITINGREP)
return 0;
switch(buf[0])
{
case PICA_PROTO_INITRESPOK:
ci -> init_resp_ok = 1;
break;
case PICA_PROTO_VERDIFFER:
ci->init_resp_ok = -1;
ci->node_ver_major = buf[2];
ci->node_ver_minor = buf[3];
break;
default:
return 0;
}
return 1;
}
static unsigned int procmsg_CONNREQINC(unsigned char* buf, unsigned int nb, void* p)
{
int ret;
struct PICA_c2n *ci = (struct PICA_c2n *)p;
struct PICA_proto_msg *mp;
unsigned char *peer_id = buf + 2;
if (callbacks.accept_cb(peer_id))
{
struct PICA_c2c *_chnl;
mp = c2n_writebuf_push( ci, PICA_PROTO_CONNALLOW, PICA_PROTO_CONNALLOW_SIZE);
if (mp)
{
memcpy(mp->tail, peer_id, PICA_ID_SIZE);
}
else
return 0;
ret = c2n_alloc_c2c( ci, &_chnl, peer_id, PICA_C2C_INCOMING);
if (!ret)
return 0;
do
{
ret = PICA_write_c2n(ci);
if (PICA_OK != ret)
return 0;
}
while( ci->write_pos > 0);
ret = c2c_start(_chnl);
if (ret != PICA_OK)
return 1;
return 1;
}
else
{
mp = c2n_writebuf_push(ci, PICA_PROTO_CONNDENY, PICA_PROTO_CONNDENY_SIZE);
if (mp)
{
memcpy(mp->tail, peer_id, PICA_ID_SIZE);
}
else
return 0;//ERR_CHECK
}
return 1;
}
static unsigned int procmsg_NOTFOUND(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2n *ci = (struct PICA_c2n *)p;
struct PICA_c2c *ipt, *rq = 0;
unsigned char *peer_id = buf + 2;
//puts("procmsg_NOTFOUND");//debug
ipt = ci->chan_list_end;
while(ipt)
{
/* Same guard as procmsg_FOUND(): act only on a channel still waiting
* for the search result, so a spurious NOTFOUND from the node cannot
* tear down an already established channel found by peer_id alone.
*/
if (ipt->outgoing && ipt->state == PICA_C2C_STATE_NEW
&& memcmp(ipt->peer_id, peer_id, PICA_ID_SIZE) == 0)
{
rq = ipt;
break;
}
ipt = ipt->prev;
}
if (!rq)
return 0;// ERR_CHECK - bogus message, no such request was sent
//puts("procmsg_NOTFOUND_chkp0");//debug
PICA_close_c2c(rq);
//puts("procmsg_NOTFOUND_chkp1");//debug
callbacks.notfound_cb(peer_id);
return 1;
}
static unsigned int procmsg_FOUND(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2n *ci = (struct PICA_c2n *)p;
struct PICA_c2c *ipt, *rq = 0;
unsigned char *peer_id = buf + 2;
int ret;
ipt = ci->chan_list_end;
while(ipt)
{
/* Only a freshly requested outgoing channel is waiting for FOUND.
* Matching on peer_id alone would also pick up an already ACTIVE
* channel and let c2c_start() tear it back down to an anonymous
* session, flushing any buffered end-to-end message to the node.
*/
if (ipt->outgoing && ipt->state == PICA_C2C_STATE_NEW
&& memcmp(ipt->peer_id, peer_id, PICA_ID_SIZE) == 0)
{
rq = ipt;
break;
}
ipt = ipt->prev;
}
if (!rq)
return 0;// ERR_CHECK - bogus message, no such request was sent
ret = c2c_start(rq);
if (ret != PICA_OK)
return 0;
return 1;
}
static unsigned int procmsg_CLNODELIST(unsigned char* buf, unsigned int nb, void* p)
{
PICA_TRACEFUNC
unsigned int pos = 4;
char ipaddr_string[INET6_ADDRSTRLEN];
char temp_zeroswap;
unsigned int port;
//puts("CLNODELIST");//debug
//callbacks.nodelist_cb(buf + 4, nb - 4);
do
{
switch(buf[pos])
{
case PICA_PROTO_NEWNODE_IPV4:
callbacks.nodelist_cb(
PICA_PROTO_NEWNODE_IPV4,
buf + pos + 1,
inet_ntop(AF_INET, buf + pos + 1, ipaddr_string, INET6_ADDRSTRLEN),
ntohs(*(uint16_t*)(buf + pos + 5))
);
pos += PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;
break;
case PICA_PROTO_NEWNODE_IPV6:
callbacks.nodelist_cb(
PICA_PROTO_NEWNODE_IPV6,
buf + pos + 1,
inet_ntop(AF_INET6, buf + pos + 1, ipaddr_string, INET6_ADDRSTRLEN),
ntohs(*(uint16_t*)(buf + pos + 17))
);
pos += PICA_PROTO_NODELIST_ITEM_IPV6_SIZE;
break;
case PICA_PROTO_NEWNODE_DNS:
port = ntohs(*(uint16_t*)(buf + pos + buf[pos + 1] + 2));
temp_zeroswap = buf[pos + 2 + buf[pos + 1]]; //save byte after hostname string
buf[pos + 2 + buf[pos + 1]] = '\0'; // and replace it with string terminating zero
callbacks.nodelist_cb(
PICA_PROTO_NEWNODE_DNS,
buf + pos + 2,
buf + pos + 2,
port
);
buf[pos + 2 + buf[pos + 1]] = temp_zeroswap;
pos += 4 + buf[pos + 1];
break;
default:
//puts("unknown node address type");//debug
return 0;
}
}
while(pos < nb);
return 1;
}
static unsigned int procmsg_MSGUTF8(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
struct PICA_proto_msg *mp;
if (chan->state != PICA_C2C_STATE_ACTIVE)
return 0;
callbacks.newmsg_cb(chan->peer_id, buf + 4, nb - 4, buf[0]);
//send PICA_PROTO_MSGOK
mp = c2c_writebuf_push( chan, PICA_PROTO_MSGOK, PICA_PROTO_MSGOK_SIZE);
if (mp)
{
RAND_pseudo_bytes( mp->tail, 2);
}
else
return 0;
return 1;
}
static unsigned int procmsg_MSGOK(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
/* A delivery receipt is only meaningful once the channel is active, same
* as procmsg_MSGUTF8 - the c2c stream is also parsed in the pre-active
* WAITINGREP/WAITINGC2CPROTOVER states.
*/
if (chan->state != PICA_C2C_STATE_ACTIVE)
return 0;
callbacks.msgok_cb(chan -> peer_id);
return 1;
}
unsigned int procmsg_PINGREQ(unsigned char* buf, unsigned int nb, void* p)
{
PICA_TRACEFUNC
struct PICA_c2n *ci = (struct PICA_c2n *)p;
struct PICA_proto_msg *mp;
mp = c2n_writebuf_push(ci, PICA_PROTO_PINGREP, PICA_PROTO_PINGREP_SIZE);
if (mp)
{
RAND_pseudo_bytes(mp->tail, 2);
}
else
return 0;
return 1;
}
/* Reads the address and the port following it, both in network byte order,
* for one of the "my address" callbacks. addr_str has to have room for
* INET6_ADDRSTRLEN characters.
*/
static int myaddr_parse(int af, const unsigned char *addr, char *addr_str, uint16_t *port)
{
if (!inet_ntop(af, addr, addr_str, INET6_ADDRSTRLEN))
return 0;
memcpy(port, addr + (af == AF_INET6 ? 16 : 4), 2);
*port = ntohs(*port);
return 1;
}
static unsigned int procmsg_MYTCPADDR(unsigned char* buf, unsigned int nb, void* p)
{
PICA_TRACEFUNC
struct PICA_c2n *c2n = (struct PICA_c2n *)p;
char addr_str[INET6_ADDRSTRLEN];
uint16_t port;
/* not something we asked for */
if (!c2n->tcpaddr_requested)
return 1;
c2n->tcpaddr_requested = 0;
/* the message size is fixed for each of the two types, see c2n_messages[] */
if (!myaddr_parse(buf[0] == PICA_PROTO_MYTCPADDR_IPV6 ? AF_INET6 : AF_INET, buf + 2, addr_str, &port))
return 0;
if (callbacks.tcp_address_cb)
callbacks.tcp_address_cb(c2n, buf[0], buf + 2, addr_str, port);
return 1;
}
static void udpaddr_send_probe(struct PICA_c2n *c2n)
{
unsigned char probe[PICA_PROTO_MYUDPADDRPROBE_SIZE];
probe[0] = probe[1] = PICA_PROTO_MYUDPADDRPROBE;
memcpy(probe + 2, c2n->udpaddr_token, PICA_PROTO_MYUDPADDR_TOKENSIZE);
/* The node's UDP port has the same number as the TCP port the c2n
* connection was made to. A failed send is treated like a lost datagram.
*/
sendto(c2n->udpaddr_sck, (const char*)probe, sizeof(probe), 0,
(const struct sockaddr*)&c2n->srv_addr, sizeof(c2n->srv_addr));
c2n->udpaddr_last_probe = time(0);
c2n->udpaddr_probes_sent++;
}
static unsigned int procmsg_MYUDPADDRTOKEN(unsigned char* buf, unsigned int nb, void* p)
{
PICA_TRACEFUNC
struct PICA_c2n *c2n = (struct PICA_c2n *)p;
/* not something we asked for, or the answer to a request already given up on */
if (c2n->udpaddr_state == PICA_UDPADDR_STATE_IDLE)
return 1;
/* A token arriving while an earlier one is being sent belongs to a
* request that restarted this one - the node has dropped the earlier
* token by now, so the new one is the one to use.
*/
memcpy(c2n->udpaddr_token, buf + 2, PICA_PROTO_MYUDPADDR_TOKENSIZE);
c2n->udpaddr_state = PICA_UDPADDR_STATE_PROBING;
c2n->udpaddr_probes_sent = 0;
udpaddr_send_probe(c2n);
return 1;
}
static unsigned int procmsg_MYUDPADDR(unsigned char* buf, unsigned int nb, void* p)
{
PICA_TRACEFUNC
struct PICA_c2n *c2n = (struct PICA_c2n *)p;
char addr_str[INET6_ADDRSTRLEN];
uint16_t port;
int af;
if (c2n->udpaddr_state != PICA_UDPADDR_STATE_PROBING)
return 1;
/* buf[2] is the length of the address that starts with its type at buf[3] */
if (nb < 4)
return 0;
if (buf[3] == PICA_PROTO_MYUDPADDR_IPV4 && buf[2] == PICA_PROTO_MYUDPADDR_IPV4_SIZE)
af = AF_INET;
else if (buf[3] == PICA_PROTO_MYUDPADDR_IPV6 && buf[2] == PICA_PROTO_MYUDPADDR_IPV6_SIZE)
af = AF_INET6;
else
return 0;
if (!myaddr_parse(af, buf + 4, addr_str, &port))
return 0;
/* before the callback, which is free to make another request */
c2n->udpaddr_state = PICA_UDPADDR_STATE_IDLE;
if (c2n->udpaddr_c2c)
{
struct PICA_c2c *c2c = c2n->udpaddr_c2c;
c2n->udpaddr_c2c = NULL;
PICA_media_call_learned(c2c, PICA_OK, buf + 4, buf[3], port);
}
else if (callbacks.udp_address_cb)
callbacks.udp_address_cb(c2n, PICA_OK, buf[3], buf + 4, addr_str, port);
return 1;
}
/* resends the datagram of a request in progress, and gives up on one that
* was not answered in time
*/
static void process_udpaddr(struct PICA_c2n *c2n)
{
time_t now;
if (c2n->udpaddr_state == PICA_UDPADDR_STATE_IDLE)
return;
now = time(0);
if (now - c2n->udpaddr_started > PICA_UDPADDR_TIMEOUT || now < c2n->udpaddr_started)
{
c2n->udpaddr_state = PICA_UDPADDR_STATE_IDLE;
if (c2n->udpaddr_c2c)
{
struct PICA_c2c *c2c = c2n->udpaddr_c2c;
c2n->udpaddr_c2c = NULL;
PICA_media_call_learned(c2c, PICA_ERRTIMEDOUT, NULL, 0, 0);
}
else if (callbacks.udp_address_cb)
callbacks.udp_address_cb(c2n, PICA_ERRTIMEDOUT, 0, NULL, NULL, 0);
return;
}
if (c2n->udpaddr_state == PICA_UDPADDR_STATE_PROBING
&& c2n->udpaddr_probes_sent < PICA_UDPADDR_PROBES
&& now != c2n->udpaddr_last_probe)
udpaddr_send_probe(c2n);
}
int PICA_request_tcp_address(struct PICA_c2n *c2n)
{
struct PICA_proto_msg *mp;
if (!c2n || c2n->state != PICA_C2N_STATE_CONNECTED)
return PICA_ERRINVARG;
mp = c2n_writebuf_push(c2n, PICA_PROTO_MYTCPADDRREQ, PICA_PROTO_MYTCPADDRREQ_SIZE);
if (!mp)
return PICA_ERRNOMEM;
RAND_pseudo_bytes(mp->tail, 2);
c2n->tcpaddr_requested = 1;
return PICA_OK;
}
int PICA_request_udp_address(struct PICA_c2n *c2n, SOCKET udp_sck)
{
struct PICA_proto_msg *mp;
if (!c2n || c2n->state != PICA_C2N_STATE_CONNECTED || udp_sck == (SOCKET)-1)
return PICA_ERRINVARG;
mp = c2n_writebuf_push(c2n, PICA_PROTO_MYUDPADDRREQ, PICA_PROTO_MYUDPADDRREQ_SIZE);
if (!mp)
return PICA_ERRNOMEM;
RAND_pseudo_bytes(mp->tail, 2);
c2n->udpaddr_sck = udp_sck;
c2n->udpaddr_started = time(0);
c2n->udpaddr_probes_sent = 0;
c2n->udpaddr_state = PICA_UDPADDR_STATE_WAITINGTOKEN;
/* a request of the application replaces one the library made for a
* call, which then sends its address list without that address
*/
if (c2n->udpaddr_c2c)
{
PICA_media_call_learned(c2n->udpaddr_c2c, PICA_ERRTIMEDOUT, NULL, 0, 0);
c2n->udpaddr_c2c = NULL;
}
return PICA_OK;
}
int PICA_deny_file(struct PICA_c2c *chan)
{
struct PICA_proto_msg *mp;
if (chan->recvfilestate != PICA_CHANRECVFILESTATE_WAITACCEPT)
return PICA_ERRINVARG;
chan->recvfilestate = PICA_CHANRECVFILESTATE_IDLE;
mp = c2c_writebuf_push(chan, PICA_PROTO_DENIEDFILE, PICA_PROTO_DENIEDFILE_SIZE);
if (mp)
{
RAND_pseudo_bytes(mp->tail, 2);
}
else
return PICA_ERRNOMEM;
return PICA_OK;
}
int PICA_accept_file(struct PICA_c2c *chan, char *filename, unsigned int filenamesize)
{
struct PICA_proto_msg *mp;
int ret;
if (chan->recvfilestate != PICA_CHANRECVFILESTATE_WAITACCEPT)
return PICA_ERRINVARG;
//open file
ret = PICA_recvfile_open_write(chan, filename, filenamesize);
if (ret != PICA_OK)
return ret;
mp = c2c_writebuf_push(chan, PICA_PROTO_ACCEPTEDFILE, PICA_PROTO_ACCEPTEDFILE_SIZE);
if (mp)
{
RAND_pseudo_bytes(mp->tail, 2);
}
else
return PICA_ERRNOMEM;
chan->recvfilestate = PICA_CHANRECVFILESTATE_RECEIVING;
return PICA_OK;
}
static int validate_file_name(const char *buf, unsigned int len)
{
int ret = PICA_OK;
char *str = malloc(len + 1);
if (!str)
return PICA_ERRNOMEM;
memcpy(str, buf, len);
str[len] = '\0';
/* TODO Unicode canonicalization */
if (strchr(str, '*') != NULL
|| strchr(str, ':') != NULL
|| strchr(str, '/') != NULL
|| strstr(str, "..") != NULL)
ret = PICA_ERRINVARG;
free(str);
return ret;
}
static unsigned int procmsg_SENDFILEREQUEST(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
struct PICA_proto_msg *mp;
int ret;
char *filename = buf + 12;
uint16_t payload_len = *(uint16_t*)(buf + 2);
unsigned int filenamesize;
if (chan->recvfilestate != PICA_CHANRECVFILESTATE_IDLE)
return 0;
/* payload = 8-byte file size + file name. Guard the subtraction so a
* short length field cannot underflow filenamesize to ~4 GB, and hold
* the sender to the documented name-length limit.
*/
if (payload_len < 8)
return 0;
filenamesize = payload_len - 8;
if (filenamesize == 0 || filenamesize > PICA_PROTO_C2CMSG_MAXFILENAMESIZE)
return 0;
if (validate_file_name(filename, filenamesize) != PICA_OK)
return 0;
chan->recvfilestate = PICA_CHANRECVFILESTATE_WAITACCEPT;
chan->recvfile_size = *(uint64_t*)(buf + 4);
chan->recvfile_pos = 0;
ret = callbacks.accept_file_cb(chan->peer_id, *(uint64_t*)(buf + 4), filename, filenamesize);
if (ret > 0)
{
if (ret == 1)
{
if (PICA_accept_file(chan, filename, filenamesize) != PICA_OK)
if (PICA_deny_file(chan) != PICA_OK)
return 0;
}
}
else
{
if (PICA_deny_file(chan) != PICA_OK)
return 0;
}
return 1;
}
static unsigned int procmsg_ACCEPTEDFILE(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
if (chan->sendfilestate != PICA_CHANSENDFILESTATE_SENTREQ)
return 0;
callbacks.accepted_file_cb(chan->peer_id);
chan->sendfilestate = PICA_CHANSENDFILESTATE_SENDING;
return 1;
}
static unsigned int procmsg_DENIEDFILE(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
if (chan->sendfilestate != PICA_CHANSENDFILESTATE_SENTREQ)
return 0;
callbacks.denied_file_cb(chan->peer_id);
chan->sendfilestate = PICA_CHANSENDFILESTATE_IDLE;
fclose(chan->sendfile_stream);
chan->sendfile_stream = NULL;
return 1;
}
static unsigned int procmsg_FILEFRAGMENT(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
/*
*Allow incoming FILEFRAGMENTs while paused
*/
if (chan->recvfilestate != PICA_CHANRECVFILESTATE_RECEIVING
&& chan->recvfilestate != PICA_CHANRECVFILESTATE_PAUSED)
return 0;
if (nb - 4 != *(uint16_t*)(buf + 2))
return 0;
if (fwrite(buf + 4, nb - 4, 1, chan->recvfile_stream) != 1)
{
struct PICA_proto_msg *mp;
fclose(chan->recvfile_stream);
chan->recvfile_stream = NULL;
chan->recvfilestate = PICA_CHANRECVFILESTATE_IDLE;
if (PICA_OK != PICA_send_filecontrol(chan, PICA_PROTO_FILECONTROL_VOID, PICA_PROTO_FILECONTROL_IOERROR))
return 0;
}
chan->recvfile_pos += (nb - 4);
if (chan->recvfile_pos > chan->recvfile_size) //received more than file_size
return 0;
callbacks.file_progress_cb(chan->peer_id, 0, chan->recvfile_pos);
if (chan->recvfile_pos == chan->recvfile_size)
{
chan->recvfilestate = PICA_CHANRECVFILESTATE_IDLE;
fclose(chan->recvfile_stream);
chan->recvfile_stream = NULL;
callbacks.file_finished_cb(chan->peer_id, 0);
}
return 1;
}
static unsigned int procmsg_FILECONTROL(unsigned char* buf, unsigned int nb, void* p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
unsigned int sender_cmd, receiver_cmd;
sender_cmd = buf[2];
receiver_cmd = buf[3];
if ((chan->sendfilestate == PICA_CHANSENDFILESTATE_IDLE || chan->sendfilestate == PICA_CHANSENDFILESTATE_SENTREQ)
&& receiver_cmd != PICA_PROTO_FILECONTROL_VOID)
return 0;
if (chan->recvfilestate == PICA_CHANRECVFILESTATE_IDLE && sender_cmd != PICA_PROTO_FILECONTROL_VOID)
return 0;
switch(sender_cmd)
{
case PICA_PROTO_FILECONTROL_PAUSE:
if (chan->recvfilestate == PICA_CHANRECVFILESTATE_RECEIVING)
chan->recvfilestate = PICA_CHANRECVFILESTATE_PAUSED;
else
return 0;
break;
case PICA_PROTO_FILECONTROL_RESUME:
if (chan->recvfilestate == PICA_CHANRECVFILESTATE_PAUSED)
chan->recvfilestate = PICA_CHANRECVFILESTATE_RECEIVING;
else
return 0;
break;
case PICA_PROTO_FILECONTROL_CANCEL:
case PICA_PROTO_FILECONTROL_IOERROR:
chan->recvfilestate = PICA_CHANRECVFILESTATE_IDLE;
/* The stream exists only once the offer was accepted; a CANCEL in
* WAITACCEPT (sender withdrew a pending offer) leaves it NULL.
*/
if (chan->recvfile_stream)
{
fclose(chan->recvfile_stream);
chan->recvfile_stream = NULL;
}
break;
case PICA_PROTO_FILECONTROL_VOID:
break;
default:
return 0;
}
switch(receiver_cmd)
{
case PICA_PROTO_FILECONTROL_PAUSE:
if (chan->sendfilestate == PICA_CHANSENDFILESTATE_SENDING)
chan->sendfilestate = PICA_CHANSENDFILESTATE_PAUSED;
else
return 0;
break;
case PICA_PROTO_FILECONTROL_RESUME:
if (chan->sendfilestate == PICA_CHANSENDFILESTATE_PAUSED)
chan->sendfilestate = PICA_CHANSENDFILESTATE_SENDING;
else
return 0;
break;
case PICA_PROTO_FILECONTROL_CANCEL:
case PICA_PROTO_FILECONTROL_IOERROR:
chan->sendfilestate = PICA_CHANSENDFILESTATE_IDLE;
/* Symmetric guard: only close a stream that was actually opened. */
if (chan->sendfile_stream)
{
fclose(chan->sendfile_stream);
chan->sendfile_stream = NULL;
}
break;
case PICA_PROTO_FILECONTROL_VOID:
break;
default:
return 0;
}
callbacks.file_control_cb(chan->peer_id, sender_cmd, receiver_cmd);
return 1;
}
#ifdef PICA_MULTITHREADED
#ifdef WIN32
void locking_cb(int mode, int type, char *file, int line)
{
if (mode & CRYPTO_LOCK)
WaitForSingleObject(mt_locks[type], INFINITE);
else
ReleaseMutex(mt_locks[type]);
}
#else
unsigned long thread_id_cb(void)
{
return (unsigned long)pthread_self();
}
void locking_cb(int mode, int type, char *file, int line)
{
if (mode & CRYPTO_LOCK)
pthread_mutex_lock(&mt_locks[type]);
else
pthread_mutex_unlock(&mt_locks[type]);
}
#endif
#endif
int PICA_client_init(struct PICA_client_callbacks *clcbs)
{
struct sockaddr_in sd;
#ifdef WIN32
WSADATA wsd;
WSAStartup(MAKEWORD(2, 2), &wsd);
#endif
if (!clcbs)
return 0;
callbacks = *clcbs;
SSL_load_error_strings();
SSL_library_init();
#ifdef NO_RAND_DEV
PICA_rand_seed();
#endif
#ifdef PICA_MULTITHREADED
{
int i;
#ifdef WIN32
mt_locks = malloc(CRYPTO_num_locks() * sizeof(HANDLE));
for (i = 0; i < CRYPTO_num_locks(); i++)
mt_locks[i] = CreateMutex(NULL, FALSE, NULL);
CRYPTO_set_locking_callback(locking_cb);
#else
mt_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
memset(mt_locks, 0, CRYPTO_num_locks()*sizeof(pthread_mutex_t));
for (i = 0; i < CRYPTO_num_locks(); i++)
pthread_mutex_init(&mt_locks[i], NULL);
CRYPTO_set_id_callback(thread_id_cb);
CRYPTO_set_locking_callback(locking_cb);
#endif
}
#endif
//ctx=SSL_CTX_new(TLSv1_method());
//if (!ctx)
//;//ERR_CHECK
#ifndef WIN32
signal(SIGPIPE, SIG_IGN);
#endif
return 1;
}
static int check_pkey_passphrase(const char *pkey_file,
int (*password_cb)(char *buf, int size, int rwflag, void *userdata),
void *userdata)
{
RSA *rsa;
FILE *f;
f = fopen(pkey_file, "r");
if (!f)
return PICA_ERRINVPKEYFILE;
rsa = PEM_read_RSAPrivateKey(f, NULL, password_cb, userdata);
fclose(f);
if (!rsa)
{
unsigned long int e = ERR_get_error();
// 0x6065064 is an OpenSSL error code corresponding to decryption failure
if (e == 0x6065064 || strcmp("bad decrypt", ERR_reason_error_string(e)) == 0)
return PICA_ERRINVPKEYPASSPHRASE;
return PICA_ERRINVPKEYFILE;
}
RSA_free(rsa);
return PICA_OK;
}
int PICA_new_listener(const struct PICA_acc *acc, int local_port, struct PICA_listener **l)
{
int ret, ret_err;
struct PICA_listener *lst = NULL;
struct sockaddr_in s;
if (!acc || local_port <= 0 || local_port > 65535 || !l)
return PICA_ERRINVARG;
lst = *l = (struct PICA_listener*)calloc(sizeof(struct PICA_listener), 1);
if (!lst)
return PICA_ERRNOMEM;
lst->acc = acc;
lst->local_port = local_port;
lst->sck_listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //(1)
if (lst->sck_listener == SOCKET_ERROR)
{
ret_err = PICA_ERRSOCK;
goto error_ret_0;
}
#ifndef WIN32
{
int flag = 1;
/* Lets the port be listened on again right after a restart, while
* connections of the previous run linger in TIME_WAIT. On Windows the
* same option lets a socket take over a port that another one is
* listening on, which would hide that the port is taken.
*/
setsockopt(lst->sck_listener, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
}
#endif
IOCTLSETNONBLOCKINGSOCKET(lst->sck_listener, 1);
memset(&s, 0, sizeof(s));
s.sin_family = AF_INET;
s.sin_addr.s_addr = INADDR_ANY;
s.sin_port = htons(local_port);
ret = bind(lst->sck_listener, (const struct sockaddr*) &s, sizeof(s));//(2)
if (ret == SOCKET_ERROR)
{
ret_err = PICA_ERRSOCK;
goto error_ret_1;
}
ret = listen(lst->sck_listener, 10);
if (ret == SOCKET_ERROR)
{
ret_err = PICA_ERRSOCK;
goto error_ret_1;
}
/* The UDP port with the same number carries call media, see PICA_media.h.
* The announced port numbers are used for both protocols, so a listener
* that has only one of them is no good - the caller can try another
* number instead.
*/
ret = PICA_media_listener_new(acc, local_port, local_port, &lst->media);
if (ret != PICA_OK)
{
fprintf(stderr, "failed to open UDP port %i for call media\n", local_port);
lst->media = NULL;
ret_err = ret;
goto error_ret_1;
}
return PICA_OK;
error_ret_1: //(1)
CLOSE(lst->sck_listener);
error_ret_0: //(0)
free(lst);
*l = 0;
return ret_err;
}
/* IPv4 address of an address string, resolving a DNS name if it is one. */
static int resolve_ipv4(const char *name, in_addr_t *addr)
{
struct addrinfo h, *r;
*addr = inet_addr(name);
if (*addr != INADDR_NONE)
return PICA_OK;
memset(&h, 0, sizeof(h));
h.ai_family = AF_INET;
h.ai_socktype = SOCK_STREAM;
h.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(name, NULL, &h, &r) != 0)
return PICA_ERRDNSRESOLVE;
*addr = ((struct sockaddr_in*)r->ai_addr)->sin_addr.s_addr;
freeaddrinfo(r);
return PICA_OK;
}
int PICA_listener_set_addrlist(struct PICA_listener *l, const char *const *addrs, const int *ports, int count)
{
struct PICA_listener_addr list[PICA_DIRECTC2C_MAX_ADDRS];
int i, ret;
if (!l || count < 0 || count > PICA_DIRECTC2C_MAX_ADDRS || (count > 0 && (!addrs || !ports)))
return PICA_ERRINVARG;
for (i = 0; i < count; i++)
{
if (ports[i] <= 0 || ports[i] > 65535)
return PICA_ERRINVARG;
list[i].port = htons((uint16_t)ports[i]);
list[i].is_upnp = addrs[i] == NULL;
list[i].addr = INADDR_ANY;
if (addrs[i])
{
ret = resolve_ipv4(addrs[i], &list[i].addr);
if (ret != PICA_OK)
return ret;
}
}
memcpy(l->addrs, list, count * sizeof(list[0]));
l->addrs_count = count;
l->addrs_manual = count > 0;
return PICA_OK;
}
int PICA_listener_set_upnp_addr(struct PICA_listener *l, const char *addr, int port)
{
if (!l)
return PICA_ERRINVARG;
if (!addr)
{
l->upnp_addr = 0;
l->upnp_port = 0;
return PICA_OK;
}
if (port <= 0 || port > 65535 || inet_addr(addr) == INADDR_NONE)
return PICA_ERRINVARG;
l->upnp_addr = inet_addr(addr);
l->upnp_port = htons((uint16_t)port);
return PICA_OK;
}
int PICA_open_acc(const char *cert_file,
const char *pkey_file,
const char *dh_param_file,
int (*password_cb)(char *buf, int size, int rwflag, void *userdata),
struct PICA_acc **acc)
{
int ret, ret_err;
DH *dh = NULL;
FILE *dh_file = NULL;
struct PICA_acc *a = NULL;
if (!(cert_file && pkey_file && dh_param_file && acc))
return PICA_ERRINVARG;
a = *acc = (struct PICA_acc*)calloc(sizeof(struct PICA_acc), 1);//(1)
if (!a)
return PICA_ERRNOMEM;
a->pkey_file = strdup(pkey_file);
a->cert_file = strdup(cert_file);
a->password_cb = password_cb;
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
a->ctx = SSL_CTX_new(TLS_method());//(2)
#else
a->ctx = SSL_CTX_new(TLSv1_2_method());//(2)
#endif
if (!a->ctx)
{
ret_err = PICA_ERRSSL;
goto error_ret_1;
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
a->anon_ctx = SSL_CTX_new(TLS_method());//(3)
#else
a->anon_ctx = SSL_CTX_new(TLSv1_2_method());//(3)
#endif
if (!a->anon_ctx)
{
ret_err = PICA_ERRSSL;
goto error_ret_2;
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
/* TLS_method() on its own would negotiate the highest version both ends
* know. Narrowing it back to 1.2 is what keeps this the same protocol
* TLSv1_2_method() used to give - see PICA_TLS_MINVERSION for why the
* ceiling matters as much as the floor.
*/
if (!SSL_CTX_set_min_proto_version(a->ctx, PICA_TLS_MINVERSION) ||
!SSL_CTX_set_max_proto_version(a->ctx, PICA_TLS_MAXVERSION) ||
!SSL_CTX_set_min_proto_version(a->anon_ctx, PICA_TLS_MINVERSION) ||
!SSL_CTX_set_max_proto_version(a->anon_ctx, PICA_TLS_MAXVERSION))
{
ret_err = PICA_ERRSSL;
goto error_ret_3;
}
#endif
/* mediac2c connections, see PICA_media.h. Not fatal if it cannot be
* created - calls then keep their media on the c2c connection.
*/
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
a->dtls_ctx = SSL_CTX_new(DTLS_method());
if (a->dtls_ctx)
SSL_CTX_set_min_proto_version(a->dtls_ctx, DTLS1_2_VERSION);
#else
a->dtls_ctx = SSL_CTX_new(DTLSv1_2_method());
#endif
/* Available since openssl 1.1.0
SSL_CTX_set_security_level(a->ctx, PICA_OPENSSL_SECURUTY_LEVEL);
*/
dh_file = fopen(dh_param_file, "r");
if (dh_file)
{
dh = PEM_read_DHparams(dh_file, NULL, NULL, NULL);
fclose(dh_file);
}
else
{
ret_err = PICA_ERRINVARG;
goto error_ret_3;
}
if (1 != SSL_CTX_set_tmp_dh(a->ctx, dh) || 1 != SSL_CTX_set_tmp_dh(a->anon_ctx, dh))
{
ret_err = PICA_ERRSSL;
goto error_ret_3;
}
/* The ciphersuites Pica Pica uses are all DHE, so the DTLS context needs
* the parameters as well or it cannot take the server role.
*/
if (a->dtls_ctx && 1 != SSL_CTX_set_tmp_dh(a->dtls_ctx, dh))
{
SSL_CTX_free(a->dtls_ctx);
a->dtls_ctx = NULL;
}
DH_free(dh);
SSL_CTX_set_options(a->ctx, SSL_OP_SINGLE_DH_USE);
SSL_CTX_set_options(a->anon_ctx, SSL_OP_SINGLE_DH_USE);
if (a->dtls_ctx)
SSL_CTX_set_options(a->dtls_ctx, SSL_OP_SINGLE_DH_USE);
if (!PICA_get_id_from_cert_file(cert_file, a->id))
{
ret_err = PICA_ERRINVCERT;
goto error_ret_3;
}
ret = check_pkey_passphrase(pkey_file, password_cb, a->id);
if (ret != PICA_OK)
{
ret_err = ret;
goto error_ret_3;
}
if (password_cb)
{
SSL_CTX_set_default_passwd_cb(a->ctx, password_cb);
SSL_CTX_set_default_passwd_cb_userdata(a->ctx, a->id);
}
ret = SSL_CTX_use_certificate_file(a->ctx, cert_file, SSL_FILETYPE_PEM);
if (ret != 1)
{
ret_err = PICA_ERRSSL;
goto error_ret_3;
}
ret = SSL_CTX_use_PrivateKey_file(a->ctx, pkey_file, SSL_FILETYPE_PEM);
if (ret != 1)
{
ret_err = PICA_ERRSSL;
goto error_ret_3;
}
ret = SSL_CTX_set_cipher_list(a->ctx, PICA_TLS_CIPHERLIST);
if (ret == 1)
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ret = SSL_CTX_set_cipher_list(a->anon_ctx, PICA_TLS_ANONDHCIPHERLIST);
#else
ret = SSL_CTX_set_cipher_list(a->anon_ctx, PICA_TLS_ANONDHCIPHERLIST "@SECLEVEL=0");
#endif
if (ret != 1)
{
ret_err = PICA_ERRSSL;
goto error_ret_3;
}
/* The DTLS context authenticates the same way as a directc2c connection,
* with the same certificate, key and ciphersuites. Anything going wrong
* here only costs calls their UDP transport, so it is not reported as an
* error - the media stays on the c2c connection instead.
*/
if (a->dtls_ctx)
{
if (password_cb)
{
SSL_CTX_set_default_passwd_cb(a->dtls_ctx, password_cb);
SSL_CTX_set_default_passwd_cb_userdata(a->dtls_ctx, a->id);
}
if (1 != SSL_CTX_use_certificate_file(a->dtls_ctx, cert_file, SSL_FILETYPE_PEM)
|| 1 != SSL_CTX_use_PrivateKey_file(a->dtls_ctx, pkey_file, SSL_FILETYPE_PEM)
|| 1 != SSL_CTX_set_cipher_list(a->dtls_ctx, PICA_TLS_CIPHERLIST))
{
fprintf(stderr, "failed to set up the DTLS context, calls will not use UDP\n");
SSL_CTX_free(a->dtls_ctx);
a->dtls_ctx = NULL;
}
}
return PICA_OK;
error_ret_3:
if (a->dtls_ctx)
SSL_CTX_free(a->dtls_ctx);
SSL_CTX_free(a->anon_ctx);//(3)
error_ret_2: //(2)
SSL_CTX_free(a->ctx);
error_ret_1: //(1)
free(a->pkey_file);
free(a->cert_file);
free(a);
*acc = 0;
return ret_err;
}
static int c2n_stage2_startanontls(struct PICA_c2n *c2n)
{
int ret;
ret = SSL_set_fd(c2n->ssl_comm, c2n->sck_comm);
if (ret != 1)
return PICA_ERRSSL;
ret = SSL_connect(c2n->ssl_comm);
ret = process_async_ssl_errors(c2n->ssl_comm, ret, &c2n->want_write, 0);
if (ret != PICA_OK)
return ret;
c2n->state = PICA_C2N_STATE_WAITINGANONTLS;
return PICA_OK;
}
static int c2n_stage3_sendreq(struct PICA_c2n *c2n)
{
PICA_TRACEFUNC
struct PICA_proto_msg *mp;
puts("c2n_stage3_sendreq");//debug
mp = c2n_writebuf_push(c2n, PICA_PROTO_INITREQ, PICA_PROTO_INITREQ_SIZE);
if (mp)
{
mp->tail[0] = PICA_PROTO_VER_HIGH;
mp->tail[1] = PICA_PROTO_VER_LOW;
}
else
return PICA_ERRNOMEM;
c2n->state = PICA_C2N_STATE_WAITINGREP;
return PICA_OK;
}
static int c2n_stage4_shutdownanontls(struct PICA_c2n *c2n)
{
int ret;
ret = SSL_shutdown(c2n->ssl_comm);
if (ret < 0)
ret = process_async_ssl_errors(c2n->ssl_comm, ret, &c2n->want_write, 0);
if (ret != PICA_OK)
return ret;
c2n->state = PICA_C2N_STATE_WAITINGANONTLSSHUTDOWN;
return PICA_OK;
}
static int c2n_stage5_starttls(struct PICA_c2n *c2n)
{
PICA_TRACEFUNC
int ret;
/* Free anon ssl struct */
SSL_free(c2n->ssl_comm);
c2n->ssl_comm = SSL_new(c2n->acc->ctx);
if (!c2n->ssl_comm)
return PICA_ERRSSL;
ret = SSL_set_fd(c2n->ssl_comm, c2n->sck_comm);
if (ret != 1)
return PICA_ERRSSL;
ret = SSL_accept(c2n->ssl_comm);
if (ret == 0)
return PICA_ERRSSL;
if (ret < 0)
ret = process_async_ssl_errors(c2n->ssl_comm, ret, &c2n->want_write, 0);
if (ret != PICA_OK)
return ret;
c2n->state = PICA_C2N_STATE_WAITINGTLS;
return PICA_OK;
}
static unsigned int procmsg_MULTILOGIN(unsigned char *buf, unsigned int nb, void *p)
{
struct PICA_c2n *c2n = (struct PICA_c2n *) p;
void *sigdatas[4];
size_t sigdatalengths[4];
uint64_t timestamp;
FILE *f;
EVP_PKEY *pubkey;
X509 *x;
int ret = 0;
uint16_t payload_len = *(uint16_t*)(buf + 2);
int siglen;
unsigned char *sig;
PICA_TRACEFUNC
//TODO report invalid MULTILOGIN messages
if (payload_len <= sizeof timestamp + PICA_PROTO_NODELIST_ITEM_IPV4_SIZE)
{
fprintf(stderr, "Invalid payload size of MULTILOGIN message: %u\n", payload_len);
return 1;
}
timestamp = *(uint64_t*)(buf + 4);
if (timestamp <= c2n->multilogin_last_timestamp)
{
fprintf(stderr, "timestamp: received %lu last %lu\n", timestamp, c2n->multilogin_last_timestamp);
return 1;
}
/* The per-connection last-timestamp check above resets to 0 on every
* reconnect, so on its own it cannot stop a captured (validly signed)
* MULTILOGIN from being replayed later. Require the timestamp to be within
* PICA_TIMETOLERANCE of now as well, bounding any replay to that window.
*/
{
uint64_t now = (uint64_t) time(NULL);
if (timestamp > now + PICA_TIMETOLERANCE
|| timestamp + PICA_TIMETOLERANCE < now)
{
fprintf(stderr, "MULTILOGIN timestamp out of tolerance, ignoring\n");
return 1;
}
}
f = fopen(c2n->acc->cert_file, "r");
if (!f)
{
fprintf(stderr, "Failed to open certificate file %s\n", c2n->acc->cert_file);
return 1;
}
x = PEM_read_X509(f, 0, 0, 0);
fclose(f);
if (!x)
return 1;
pubkey = X509_get_pubkey(x);
if (!pubkey)
goto multilogin_err1;
sigdatas[0] = c2n->acc->id;
sigdatalengths[0] = PICA_ID_SIZE;
sigdatas[1] = buf + 4;
sigdatalengths[1] = sizeof(uint64_t);
sigdatas[2] = buf + 4 + sizeof(uint64_t);
switch (buf[4 + sizeof(uint64_t)])
{
case PICA_PROTO_NEWNODE_IPV4:
sigdatalengths[2] = PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;
break;
default: // IPv6 !!
goto multilogin_err2;
break;
}
sigdatas[3] = NULL;
sigdatalengths[3] = 0;
siglen = payload_len - sizeof(uint64_t) - sigdatalengths[2];
if (siglen <= 0)
goto multilogin_err2;
sig = buf + 4 + sizeof(uint64_t) + sigdatalengths[2];
ret = PICA_signverify(pubkey, sigdatas, sigdatalengths, sig, siglen);
if (ret != 1)
{
fprintf(stderr, "signature verification failed\n");
goto multilogin_err2;
}
{
char ipaddr_string[INET6_ADDRSTRLEN];
unsigned char *ipv4_pos = buf + 4 + sizeof(uint64_t) + 1;
unsigned char *port_pos = buf + 4 + sizeof(uint64_t) + 1 + 4;
callbacks.multilogin_cb(timestamp, sigdatas[2],
inet_ntop(AF_INET, ipv4_pos, ipaddr_string, INET6_ADDRSTRLEN),
ntohs(*(uint16_t*)(port_pos)));
}
c2n->multilogin_last_timestamp = timestamp;
multilogin_err2:
EVP_PKEY_free(pubkey);
multilogin_err1:
X509_free(x);
return 1;
}
/* Everything a call held, given back when it ends. */
static void call_release(struct PICA_c2c *chn)
{
chn->call_state = PICA_CALL_STATE_IDLE;
PICA_media_close(chn);
PICA_media_call_free(chn);
chn->call_audio_params_are_set = 0;
chn->call_video_params_are_set = 0;
}
/* Sends 0x70 or 0x71 with the probe token and the addresses of the call
* socket. */
static int call_send_info(struct PICA_c2c *chn, unsigned int msgid)
{
struct PICA_proto_msg *mp;
unsigned char info[PICA_MEDIA_CALL_INFO_MAXSIZE];
unsigned int len;
len = PICA_media_call_write_info(chn, info);
mp = c2c_writebuf_push(chn, msgid, 4 + len);
if (!mp)
return PICA_ERRNOMEM;
mp->tail[0] = len & 0xFF;
mp->tail[1] = (len >> 8) & 0xFF;
memcpy(mp->tail + 2, info, len);
if (chn->media_call)
chn->media_call->pending_msg = 0;
return PICA_OK;
}
static int call_send_audio_params(struct PICA_c2c *chn, const char *codec_name, uint16_t sample_rate);
static int call_send_video_params(struct PICA_c2c *chn, const char *codec_name, uint16_t width, uint16_t height);
/* 0x71 is out, the call is active for the callee now. */
static int call_answered(struct PICA_c2c *chn)
{
struct PICA_media_call *mc = chn->media_call;
int ret;
ret = call_send_info(chn, PICA_PROTO_CALLANS);
if (ret != PICA_OK)
return ret;
chn->call_state = PICA_CALL_STATE_ACTIVE;
/* the parameters set while 0x71 was waiting, which the caller must not
* see before it
*/
if (mc && mc->audio_params_pending)
call_send_audio_params(chn, mc->audio_codec, mc->audio_sample_rate);
if (mc && mc->video_params_pending)
call_send_video_params(chn, mc->video_codec, mc->video_width, mc->video_height);
if (mc)
mc->audio_params_pending = mc->video_params_pending = 0;
PICA_media_start(chn);
return PICA_OK;
}
static void call_send_reception_report(struct PICA_c2c *chn);
/* Sends 0x70 and 0x71 that were waiting for the address of the call socket
* once it is known, or once waiting for it is over, and the 0x79 reports of
* active calls.
*/
static void process_calls(struct PICA_c2n *c2n)
{
struct PICA_c2c *c2c;
for (c2c = c2n->chan_list_head; c2c; c2c = c2c->next)
{
struct PICA_media_call *mc = c2c->media_call;
if (!mc)
continue;
if (c2c->call_state == PICA_CALL_STATE_ACTIVE)
call_send_reception_report(c2c);
if (!mc->pending_msg || !PICA_media_call_ready(c2c))
continue;
if (mc->pending_msg == PICA_PROTO_CALLREQ && c2c->call_state == PICA_CALL_STATE_CALLING)
call_send_info(c2c, PICA_PROTO_CALLREQ);
else if (mc->pending_msg == PICA_PROTO_CALLANS && c2c->call_state == PICA_CALL_STATE_ANSWERING)
call_answered(c2c);
else
mc->pending_msg = 0;
}
}
static unsigned int procmsg_CALLREQ(unsigned char* buf, unsigned int nb, void *p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
if (chan->call_state != PICA_CALL_STATE_IDLE)
// busy, send reject
{
struct PICA_proto_msg *mp;
mp = c2c_writebuf_push( chan, PICA_PROTO_CALLREJ, PICA_PROTO_CALLREJ_SIZE);
if (mp)
{
RAND_pseudo_bytes( mp->tail, 2);
}
else
return 0;
return 1;
}
/* The callee starts finding out the address of its call socket now,
* while the call rings, so that answering is not held up by it. A call
* that cannot have it still rings.
*/
PICA_media_call_prepare(chan, 0, buf + 4, nb - 4);
chan->call_state = PICA_CALL_STATE_INCOMINGCALL;
if (chan->media_call)
callbacks.incoming_call_cb(chan->peer_id, chan->media_call->peer_recommended_width,
chan->media_call->peer_recommended_height);
else
callbacks.incoming_call_cb(chan->peer_id, 0, 0);
return 1;
}
static unsigned int procmsg_CALLANS(unsigned char* buf, unsigned int nb, void *p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
if (chan->call_state != PICA_CALL_STATE_CALLING)
{
fprintf(stderr, "unexpected CALLANS, we did not initiate a call");
return 0;
}
/* a malformed list only costs the call its hole punching */
PICA_media_call_read_info(chan, buf + 4, nb - 4);
chan->call_state = PICA_CALL_STATE_ACTIVE;
if (chan->media_call)
callbacks.call_picked_up_cb(chan->peer_id, chan->media_call->peer_recommended_width,
chan->media_call->peer_recommended_height);
else
callbacks.call_picked_up_cb(chan->peer_id, 0, 0);
PICA_media_start(chan);
return 1;
}
static unsigned int procmsg_CALLREJ(unsigned char* buf, unsigned int nb, void *p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
if (chan->call_state != PICA_CALL_STATE_CALLING)
{
fprintf(stderr, "unexpected CALLREJ, we did not initiate a call");
return 0;
}
call_release(chan);
callbacks.call_rejected_cb(chan->peer_id);
return 1;
}
static unsigned int procmsg_CALLFIN(unsigned char* buf, unsigned int nb, void *p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
if (chan->call_state == PICA_CALL_STATE_IDLE)
{
fprintf(stderr, "unexpected CALLFIN, no call in progress");
return 0;
}
call_release(chan);
callbacks.call_hangup_cb(chan->peer_id);
return 1;
}
static unsigned int procmsg_CALL_AUDIOPARAM(unsigned char* buf, unsigned int nb, void *p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
char codecnamebuf[24];
uint16_t sample_rate;
if (chan->call_state != PICA_CALL_STATE_ACTIVE)
{
fprintf(stderr, "unexpected AUDIOPARAM, no call in progress");
return 0;
}
chan->call_audio_params_are_set = 1;
codecnamebuf[0] = '\0';
strncat(codecnamebuf, buf + 2, PICA_PROTO_CALL_CODECNAMESIZE);
sample_rate = *(uint16_t*)(buf + 2 + PICA_PROTO_CALL_CODECNAMESIZE);
callbacks.call_audio_params_cb(chan->peer_id, codecnamebuf, sample_rate);
return 1;
}
static unsigned int procmsg_CALL_VIDEOPARAM(unsigned char* buf, unsigned int nb, void *p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
char codecnamebuf[24];
uint16_t width, height;
if (chan->call_state != PICA_CALL_STATE_ACTIVE)
{
fprintf(stderr, "unexpected VIDEOPARAM, no call in progress");
return 0;
}
chan->call_video_params_are_set = 1;
codecnamebuf[0] = '\0';
strncat(codecnamebuf, buf + 2, PICA_PROTO_CALL_CODECNAMESIZE);
width = *(uint16_t*)(buf + 2 + PICA_PROTO_CALL_CODECNAMESIZE);
height = *(uint16_t*)(buf + 2 + PICA_PROTO_CALL_CODECNAMESIZE + 2);
callbacks.call_video_params_cb(chan->peer_id, codecnamebuf, width, height);
return 1;
}
/* A media packet is dropped rather than treated as a protocol error breaking
* the connection. It can legitimately arrive when the receiving side is not
* ready for it: over a mediac2c connection it can overtake the 0x74/0x75
* message describing its stream, which travels over the c2c connection, and
* it can also arrive after a call has already been hung up locally. A
* malformed packet is dropped for the same reason - over UDP it says nothing
* about the peer.
*/
static unsigned int procmsg_CALL_AUDIO_PACKET(unsigned char *buf, unsigned int nb, void* p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
if (chan->call_state != PICA_CALL_STATE_ACTIVE)
{
fprintf(stderr, "unexpected CALL_AUDIO_PACKET, no call in progress\n");
return 1;
}
if (!chan->call_audio_params_are_set)
{
fprintf(stderr, "no AUDIOPARAM was set, can't process AUDIO_PACKET\n");
return 1;
}
if (*(uint16_t*)(buf + 2) != (nb - 4))
{
return 1;
}
uint16_t tail_size = *(uint16_t*)(buf + 2);
if (tail_size < PICA_PROTO_CALL_PACKET_HDRSIZE)
{
return 1;
}
uint16_t seq_num = *(uint16_t*)(buf + 4);
uint32_t timestamp = *(uint32_t*)(buf + 4 + PICA_PROTO_CALL_PACKET_SEQNUM_SIZE);
uint16_t pkt_size = tail_size - PICA_PROTO_CALL_PACKET_HDRSIZE;
PICA_media_rx_packet(chan, 0, seq_num, timestamp, pkt_size);
callbacks.call_audio_packet_cb(chan->peer_id, seq_num, timestamp, pkt_size, buf + 4 + PICA_PROTO_CALL_PACKET_HDRSIZE);
return 1;
}
static unsigned int procmsg_CALL_VIDEO_PACKET(unsigned char *buf, unsigned int nb, void *p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
if (chan->call_state != PICA_CALL_STATE_ACTIVE)
{
fprintf(stderr, "unexpected CALL_VIDEO_PACKET, no call in progress\n");
return 1;
}
if (!chan->call_video_params_are_set)
{
fprintf(stderr, "no VIDEOPARAM was set, can't process VIDEO_PACKET\n");
return 1;
}
if (*(uint16_t*)(buf + 2) != (nb - 4))
{
return 1;
}
uint16_t tail_size = *(uint16_t*)(buf + 2);
if (tail_size < PICA_PROTO_CALL_PACKET_HDRSIZE)
{
return 1;
}
uint16_t seq_num = *(uint16_t*)(buf + 4);
uint32_t timestamp = *(uint32_t*)(buf + 4 + PICA_PROTO_CALL_PACKET_SEQNUM_SIZE);
uint16_t pkt_size = tail_size - PICA_PROTO_CALL_PACKET_HDRSIZE;
PICA_media_rx_packet(chan, 1, seq_num, timestamp, pkt_size);
callbacks.call_video_packet_cb(chan->peer_id, seq_num, timestamp, pkt_size, buf + 4 + PICA_PROTO_CALL_PACKET_HDRSIZE);
return 1;
}
static uint16_t get_le16(const unsigned char *p)
{
return (uint16_t)(p[0] | (p[1] << 8));
}
static uint32_t get_le32(const unsigned char *p)
{
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
static void put_le16(unsigned char *p, uint16_t v)
{
p[0] = v & 0xFF;
p[1] = (v >> 8) & 0xFF;
}
static void put_le32(unsigned char *p, uint32_t v)
{
p[0] = v & 0xFF;
p[1] = (v >> 8) & 0xFF;
p[2] = (v >> 16) & 0xFF;
p[3] = (v >> 24) & 0xFF;
}
/* Ignored rather than a protocol error outside of an active call: one sent
* just before the peer learnt that the call is over is still on its way when
* the hangup has already been processed here.
*/
static unsigned int procmsg_CALL_RECEPTION_REPORT(unsigned char *buf, unsigned int nb, void *p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
struct PICA_call_reception_report r;
if (chan->call_state != PICA_CALL_STATE_ACTIVE)
return 1;
r.period = get_le16(buf + 2);
r.audio_received = get_le16(buf + 4);
r.audio_lost = get_le16(buf + 6);
r.video_received = get_le16(buf + 8);
r.video_lost = get_le16(buf + 10);
r.audio_octets = get_le32(buf + 12);
r.video_octets = get_le32(buf + 16);
r.queuing_delay = get_le16(buf + 20);
if (callbacks.call_reception_report_cb)
callbacks.call_reception_report_cb(chan->peer_id, &r);
return 1;
}
/* Sends 0x79 when a report period of the call is over. */
static void call_send_reception_report(struct PICA_c2c *chn)
{
struct PICA_call_reception_report r;
struct PICA_proto_msg *mp;
if (!PICA_media_rx_report(chn, &r))
return;
/* Over the c2c connection, or the directc2c one once it has taken over,
* whatever carries the media: the report has to arrive even when the
* media connection is losing most of what it carries.
*/
mp = c2c_writebuf_push(chn, PICA_PROTO_CALL_RECEPTION_REPORT, PICA_PROTO_CALL_RECEPTION_REPORT_SIZE);
if (!mp)
return;
put_le16(mp->tail + 0, r.period);
put_le16(mp->tail + 2, r.audio_received);
put_le16(mp->tail + 4, r.audio_lost);
put_le16(mp->tail + 6, r.video_received);
put_le16(mp->tail + 8, r.video_lost);
put_le32(mp->tail + 10, r.audio_octets);
put_le32(mp->tail + 14, r.video_octets);
put_le16(mp->tail + 18, r.queuing_delay);
}
static int c2n_optstage7_multilogin(struct PICA_c2n *c2n)
{
struct PICA_proto_msg *mp;
void *sigdatas[4];
size_t sigdatalengths[4];
uint64_t timestamp;
unsigned char node_addr[PICA_PROTO_NODELIST_ITEM_IPV4_SIZE];
size_t siglen;
unsigned char *sig = NULL;
EVP_PKEY *pkey = NULL;
RSA *rsa = NULL;
FILE *f;
int ret = PICA_ERRNOMEM;
PICA_TRACEFUNC
sigdatas[0] = c2n->acc->id;
sigdatalengths[0] = PICA_ID_SIZE;
timestamp = (uint64_t) time(NULL);
sigdatas[1] = ×tamp;
sigdatalengths[1] = sizeof timestamp;
fprintf(stderr, "timestamp = %lu\n", timestamp);
//nodeaddr buf, IPv4 for now
// TODO IPv6, DNS
node_addr[0] = PICA_PROTO_NEWNODE_IPV4;
memcpy(node_addr + 1, &c2n->srv_addr.sin_addr.s_addr, 4);
memcpy(node_addr + 5, &c2n->srv_addr.sin_port, 2);
sigdatas[2] = node_addr;
sigdatalengths[2] = PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;
sigdatas[3] = NULL;
sigdatalengths[3] = 0;
pkey = EVP_PKEY_new();
if (!pkey)
goto sendmultilogin_exit1;
f = fopen(c2n->acc->pkey_file, "r");
if (!f)
{
ret = PICA_ERRFILEOPEN;
goto sendmultilogin_exit2;
}
ret = PICA_ERRSSL;
rsa = PEM_read_RSAPrivateKey(f, NULL, c2n->acc->password_cb, c2n->acc->id);
fclose(f);
if (!rsa)
goto sendmultilogin_exit2;
ret = EVP_PKEY_set1_RSA(pkey, rsa);
if (ret != 1)
goto sendmultilogin_exit3;
ret = PICA_do_signature(pkey, sigdatas, sigdatalengths, &sig, &siglen);
if (ret != 1)
goto sendmultilogin_exit4;
if (siglen > PICA_PROTO_MULTILOGIN_MAXSIGSIZE)
{
ret = PICA_ERRMSGSIZE;
goto sendmultilogin_exit4;
}
mp = c2n_writebuf_push(c2n, PICA_PROTO_MULTILOGIN, 2 + 2 + sizeof timestamp + sigdatalengths[2] + siglen);
if (mp)
{
*((uint16_t*)mp->tail) = sizeof timestamp + sigdatalengths[2] + siglen;
memcpy(mp->tail + 2, ×tamp, sizeof timestamp);
fprintf(stderr, "timestamp = %lu\n", timestamp);
memcpy(mp->tail + 2 + sizeof timestamp, sigdatas[2], sigdatalengths[2]);
memcpy(mp->tail + 2 + sizeof timestamp + sigdatalengths[2], sig, siglen);
ret = PICA_OK;
}
else
ret = PICA_ERRNOMEM;
sendmultilogin_exit4:
free(sig);
sendmultilogin_exit3:
RSA_free(rsa);
sendmultilogin_exit2:
EVP_PKEY_free(pkey);
sendmultilogin_exit1:
return ret;
}
static int c2n_stage6_nodelistrequest(struct PICA_c2n *c2n)
{
PICA_TRACEFUNC
struct PICA_proto_msg *mp;
mp = c2n_writebuf_push(c2n, PICA_PROTO_CLNODELISTREQ, PICA_PROTO_CLNODELISTREQ_SIZE);
if (mp)
{
RAND_pseudo_bytes(mp->tail, 2);
}
else
return PICA_ERRNOMEM;
c2n->state = PICA_C2N_STATE_CONNECTED;
callbacks.c2n_established_cb(c2n);
if (c2n->multilogin_policy != PICA_MULTILOGIN_PROHIBIT)
return c2n_optstage7_multilogin(c2n);
return PICA_OK;
}
static int directc2c_stage2_starttls(struct PICA_directc2c *d, struct PICA_c2c *c2c)
{
PICA_TRACEFUNC
int ret;
d->ssl = SSL_new(c2c->acc->ctx);
SSL_set_fd(d->ssl, d->sck);
SSL_set_verify(d->ssl, SSL_VERIFY_PEER, PICA_verify_callback);
SSL_set_verify_depth(d->ssl, 1);
ret = SSL_connect(d->ssl);
if (ret == 0)
return PICA_ERRSSL;
if (ret < 0)
{
ret = SSL_get_error(d->ssl, ret);
if (ret != SSL_ERROR_WANT_READ && ret != SSL_ERROR_WANT_WRITE)
return PICA_ERRSSL;
}
d->state = PICA_DIRECTC2C_CONNSTATE_WAITINGTLS;
return PICA_OK;
}
void PICA_c2n_set_directc2c(struct PICA_c2n *c2n, enum PICA_directc2c_config direct_c2c_mode,
struct PICA_listener *l)
{
c2n->directc2c_config = direct_c2c_mode;
c2n->directc2c_listener = direct_c2c_mode == PICA_DIRECTC2C_CFG_ALLOWINCOMING ? l : NULL;
}
int PICA_new_c2n(const struct PICA_acc *acc, const char *nodeaddr, unsigned int port,
enum PICA_directc2c_config direct_c2c_mode, int multilogin,
struct PICA_listener *l, struct PICA_c2n **ci)
{
PICA_TRACEFUNC
int ret, ret_err;
struct PICA_c2n *cid;
struct sockaddr_in a;
if (!(nodeaddr && acc && port && ci))
return PICA_ERRINVARG;
cid = *ci = (struct PICA_c2n*)calloc(sizeof(struct PICA_c2n), 1); //(1)
if (!cid)
return PICA_ERRNOMEM;
cid->acc = acc;
PICA_c2n_set_directc2c(cid, direct_c2c_mode, l);
cid->multilogin_policy = multilogin;
cid->read_buf = calloc(PICA_CONNREADBUFSIZE, 1);//(2)
if (!cid->read_buf)
{
ret_err = PICA_ERRNOMEM;
goto error_ret_1;
}
cid->ssl_comm = SSL_new(acc->anon_ctx); //(3)
if (!cid->ssl_comm)
{
ret_err = PICA_ERRSSL;
goto error_ret_2;
}
//resolving name
{
struct addrinfo h, *r;
memset(&h, 0, sizeof(struct addrinfo));
h.ai_flags = 0;
#ifdef AI_IDN
h.ai_flags = h.ai_flags | AI_IDN;
#endif
#ifdef AI_ADDRCONFIG
h.ai_flags = h.ai_flags | AI_ADDRCONFIG;
#endif
h.ai_family = AF_INET; //CONF
h.ai_socktype = SOCK_STREAM;
h.ai_protocol = IPPROTO_TCP;
if (0 != getaddrinfo(nodeaddr, NULL, &h, &r))
{
ret_err = PICA_ERRDNSRESOLVE;
goto error_ret_4;
}
memset(&a, 0, sizeof(a));
memcpy(&a, r->ai_addr, r->ai_addrlen);
a.sin_family = AF_INET;
//a.sin_addr.s_addr = inet_addr (nodeaddr);
a.sin_port = htons(port);
freeaddrinfo(r);
}
cid->srv_addr = a;
cid->sck_comm = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //(5)
if (cid->sck_comm == SOCKET_ERROR)
{
ret_err = PICA_ERRSOCK;
goto error_ret_3;
}
IOCTLSETNONBLOCKINGSOCKET(cid->sck_comm, 1);
SETTCPNODELAY(cid->sck_comm);
cid->state = PICA_C2N_STATE_CONNECTING;
ret = connect(cid->sck_comm, (struct sockaddr*)&cid->srv_addr, sizeof(cid->srv_addr));
if (ret == 0)
return c2n_stage2_startanontls(cid);
if ((ret_err = process_first_async_connect_result(ret)) != PICA_OK)
goto error_ret_4;
return PICA_OK;
error_ret_4: //(4)
SHUTDOWN(cid->sck_comm);
CLOSE(cid->sck_comm);
error_ret_3: //(3)
SSL_free(cid->ssl_comm);
error_ret_2: //(2)
free(cid->read_buf);
error_ret_1: //(1)
free(cid);
*ci = 0;
return ret_err;
}
int PICA_new_c2c(struct PICA_c2n *ci, const unsigned char *peer_id, struct PICA_listener *l, struct PICA_c2c **chn)
{
PICA_TRACEFUNC
struct PICA_proto_msg *mp;
struct PICA_c2c *chnl;
if (!(ci && chn))
return PICA_ERRINVARG;
if (ci->state != PICA_C2N_STATE_CONNECTED)
return PICA_ERRINVARG;
if (!c2n_alloc_c2c(ci, chn, peer_id, PICA_C2C_OUTGOING))
return PICA_ERRNOMEM;
chnl = *chn;
mp = c2n_writebuf_push( ci, PICA_PROTO_CONNREQOUTG, PICA_PROTO_CONNREQOUTG_SIZE);
if (mp)
{
memcpy(mp->tail, peer_id, PICA_ID_SIZE);
}
else
return PICA_ERRNOMEM;
return PICA_OK;
}
static int process_async_ssl_errors(SSL *ssl, int ret, int *want_write, int *want_read)
{
PICA_TRACEFUNC
if (ret == 0)
return PICA_ERRDISCONNECT;
if (ret < 0)
switch(SSL_get_error(ssl, ret))
{
case SSL_ERROR_WANT_WRITE:
if (want_write)
*want_write = 1;
break;
case SSL_ERROR_WANT_READ:
if (want_read)
*want_read = 1;
break;
default:
return PICA_ERRSSL;
};
return PICA_OK;
}
static int process_first_async_connect_result(int connect_ret)
{
PICA_TRACEFUNC
if (connect_ret == SOCKET_ERROR)
{
#ifndef WIN32
if (errno == EINPROGRESS || errno == EINTR)
return PICA_OK;
#else
if (WSAGetLastError() == WSAEWOULDBLOCK)
return PICA_OK;
#endif
return PICA_ERRSOCK;
}
return PICA_OK;
}
static int check_async_connect_result(int sock, struct sockaddr* a, int addrlen)
{
PICA_TRACEFUNC
int ret = PICA_ERRSOCK;
#ifndef WIN32
int optval;
socklen_t optlen = sizeof(optval);
if (0 == getsockopt(sock, SOL_SOCKET, SO_ERROR, &optval, &optlen) && optval == 0)
#else
if (SOCKET_ERROR == connect(sock, a, addrlen) &&
WSAEISCONN == WSAGetLastError())
#endif
ret = PICA_OK;
return ret;
}
static int process_c2n(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds)
{
int ret = PICA_OK;
//puts("process_c2n()");//debug
switch(c2n->state)
{
case PICA_C2N_STATE_NEW:
break;
case PICA_C2N_STATE_CONNECTING:
if (FD_ISSET(c2n->sck_comm, wfds))
{
ret = check_async_connect_result(c2n->sck_comm, (struct sockaddr*)&c2n->srv_addr, sizeof(c2n->srv_addr));
if (ret == PICA_OK)
{
ret = c2n_stage2_startanontls(c2n);
}
}
break;
case PICA_C2N_STATE_WAITINGANONTLS:
if (FD_ISSET(c2n->sck_comm, wfds) || FD_ISSET(c2n->sck_comm, rfds))
{
int sslret;
sslret = SSL_connect(c2n->ssl_comm);
if (sslret == 1)
ret = c2n_stage3_sendreq(c2n);
else
{
ret = process_async_ssl_errors(c2n->ssl_comm, sslret, &c2n->want_write, 0);
}
}
break;
case PICA_C2N_STATE_WAITINGREP:
if (FD_ISSET(c2n->sck_comm, wfds))
{
ret = PICA_write_c2n(c2n);
}
if (FD_ISSET(c2n->sck_comm, rfds))
{
ret = PICA_read_c2n(c2n);
}
if (ret == PICA_OK && c2n->init_resp_ok != 0)
{
if (c2n->init_resp_ok == 1)
ret = c2n_stage4_shutdownanontls(c2n);
else
{
if (c2n->node_ver_major > PICA_PROTO_VER_HIGH ||
(c2n->node_ver_major == PICA_PROTO_VER_HIGH && c2n->node_ver_minor > PICA_PROTO_VER_LOW))
ret = PICA_ERRPROTONEW;
else
ret = PICA_ERRPROTOOLD;
}
}
break;
case PICA_C2N_STATE_WAITINGANONTLSSHUTDOWN:
if (FD_ISSET(c2n->sck_comm, wfds) || FD_ISSET(c2n->sck_comm, rfds))
{
int sslret;
sslret = SSL_shutdown(c2n->ssl_comm);
if (sslret == 0)
break;
if (sslret < 0)
ret = process_async_ssl_errors(c2n->ssl_comm, sslret, &c2n->want_write, 0);
if (sslret == 1)
ret = c2n_stage5_starttls(c2n);
}
break;
case PICA_C2N_STATE_WAITINGTLS:
if (FD_ISSET(c2n->sck_comm, wfds) || FD_ISSET(c2n->sck_comm, rfds))
{
int sslret;
sslret = SSL_accept(c2n->ssl_comm);
if (sslret == 1)
ret = c2n_stage6_nodelistrequest(c2n);
else if (sslret == 0)
ret = PICA_ERRSSL;
else if (sslret < 0)
ret = process_async_ssl_errors(c2n->ssl_comm, sslret, &c2n->want_write, 0);
}
break;
case PICA_C2N_STATE_CONNECTED:
if (FD_ISSET(c2n->sck_comm, wfds))
ret = PICA_write_c2n(c2n);
if (FD_ISSET(c2n->sck_comm, rfds))
ret = PICA_read_c2n(c2n);
break;
}
return ret;
}
static int process_c2c(struct PICA_c2c *c2c, fd_set *rfds, fd_set *wfds)
{
int ret = PICA_OK;
switch(c2c->state)
{
case PICA_C2C_STATE_NEW:
break;
case PICA_C2C_STATE_CONNECTING:
if (FD_ISSET(c2c->sck_data, wfds))
{
ret = check_async_connect_result(c2c->sck_data, (struct sockaddr*)&c2c->conn->srv_addr, sizeof(c2c->conn->srv_addr));
if (ret == PICA_OK)
{
ret = c2c_stage2_startanontls(c2c);
}
}
break;
case PICA_C2C_STATE_WAITINGANONTLS:
if (FD_ISSET(c2c->sck_data, wfds) || FD_ISSET(c2c->sck_data, rfds))
{
int sslret;
sslret = SSL_connect(c2c->ssl);
if (sslret == 1)
ret = c2c_stage3_connid(c2c);
else
{
ret = process_async_ssl_errors(c2c->ssl, sslret, &c2c->want_write, NULL);
}
}
break;
case PICA_C2C_STATE_CONNID:
if (FD_ISSET(c2c->sck_data, wfds))
{
ret = PICA_write_c2c(c2c);
}
if (c2c->write_pos == 0)
{
ret = c2c_stage4_shutdownanontls(c2c);
}
break;
case PICA_C2C_STATE_WAITINGANONTLSSHUTDOWN:
if (FD_ISSET(c2c->sck_data, wfds) || FD_ISSET(c2c->sck_data, rfds))
{
int sslret;
sslret = SSL_shutdown(c2c->ssl);
if (sslret == 0)
break;
if (sslret < 0)
ret = process_async_ssl_errors(c2c->ssl, sslret, &c2c->want_write, NULL);
if (sslret == 1)
ret = c2c_stage5_starttls(c2c);
}
break;
case PICA_C2C_STATE_WAITINGTLS:
if (FD_ISSET(c2c->sck_data, wfds) || FD_ISSET(c2c->sck_data, rfds))
{
int sslret;
if (c2c->outgoing)
sslret = SSL_connect(c2c->ssl);
else
sslret = SSL_accept(c2c->ssl);
if (sslret < 0)
{
sslret = SSL_get_error(c2c->ssl, sslret);
if (sslret != SSL_ERROR_WANT_READ && sslret != SSL_ERROR_WANT_WRITE)
ret = PICA_ERRSSL;
if (sslret == SSL_ERROR_WANT_WRITE)
c2c->want_write = 1;
}
else if(sslret == 0)
{
ret = PICA_ERRSSL;
}
else if (sslret == 1)
{
ret = c2c_verify_peer_cert(c2c);
if (ret == PICA_OK && c2c->outgoing)
ret = c2c_stage6_sendc2cconnreq(c2c);
if (ret == PICA_OK && c2c->outgoing == 0)
c2c->state = PICA_C2C_STATE_WAITINGC2CPROTOVER;
}
}
break;
case PICA_C2C_STATE_WAITINGREP:
case PICA_C2C_STATE_WAITINGC2CPROTOVER:
if (FD_ISSET(c2c->sck_data, wfds))
{
ret = PICA_write_c2c(c2c);
}
if (ret == PICA_OK && FD_ISSET(c2c->sck_data, rfds))
{
ret = PICA_read_c2c(c2c);
}
break;
case PICA_C2C_STATE_ACTIVE:
if (FD_ISSET(c2c->sck_data, wfds)
|| c2c->directc2c_state == PICA_DIRECTC2C_STATE_ACTIVE && FD_ISSET(c2c->direct->sck, wfds))
{
if (c2c->sendfilestate == PICA_CHANSENDFILESTATE_SENDING && c2c->write_pos == 0)
{
ret = PICA_send_file_fragment(c2c);
}
if (c2c->write_pos > 0)
{
ret = PICA_write_c2c(c2c);
}
}
if (ret == PICA_OK && (FD_ISSET(c2c->sck_data, rfds)
|| c2c->directc2c_state == PICA_DIRECTC2C_STATE_ACTIVE && FD_ISSET(c2c->direct->sck, rfds)))
{
ret = PICA_read_c2c(c2c);
}
break;
}
if (c2c->state != PICA_C2C_STATE_ACTIVE && (time(0) - c2c->timestamp) > PICA_C2C_ACTIVATE_TIMEOUT)
{
ret = PICA_ERRTIMEDOUT;
}
if (ret != PICA_OK)
{
if (c2c->state > PICA_C2C_STATE_NEW && c2c->state < PICA_C2C_STATE_ACTIVE)
callbacks.c2c_failed_cb(c2c->peer_id);
else
callbacks.c2c_closed_cb(c2c->peer_id, ret);
}
return ret;
}
static struct PICA_c2c * find_matching_c2c(struct PICA_c2n *c2n, struct PICA_directc2c *d)
{
PICA_TRACEFUNC
struct PICA_c2c *c2c;
unsigned char idbuf[PICA_ID_SIZE];
if (!PICA_id_from_X509(d->peer_cert, idbuf))
return NULL;
c2c = c2n->chan_list_head;
while(c2c)
{
if (c2c->directc2c_state == PICA_DIRECTC2C_STATE_WAITINGINCOMING)
{
if (memcmp(idbuf, c2c->peer_id, PICA_ID_SIZE) == 0)
{
return c2c;
}
}
c2c = c2c->next;
}
return NULL;
}
static int directc2c_verify_peer_cert(struct PICA_directc2c *d, struct PICA_c2c *c2c)
{
PICA_TRACEFUNC
return PICA_verify_peer_cert_common(&d->peer_cert, d->ssl, c2c->peer_id);
}
static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds)
{
struct PICA_directc2c *d;
struct PICA_c2c *c2c = NULL;
int ret;
//process accepted connections
if (c2n->directc2c_listener)
{
struct PICA_directc2c **pdprev;
d = c2n->directc2c_listener->accepted_connections;
pdprev = &c2n->directc2c_listener->accepted_connections;
while(d)
{
struct PICA_directc2c *dnext = d->next;
if (d->state == PICA_DIRECTC2C_CONNSTATE_ACTIVE)
{
/* d leaves the listener list either way - adopted by a c2c or
* closed. Splice it out first, using the next pointer captured
* above, so nothing is read back out of a freed node.
*/
*pdprev = dnext;
d->next = NULL;
char addrstr[PICA_DIRECTC2C_ADDRSTRSIZE];
directc2c_addrstr(&d->addr, addrstr);
if ((c2c = find_matching_c2c(c2n, d)) && (PICA_verify_peer_cert_common(&d->peer_cert, d->ssl, c2c->peer_id) == PICA_OK))
{
fprintf(stderr, "directc2c: incoming connection from %s accepted\n", addrstr);
if (c2c->direct)
PICA_close_directc2c(c2c->direct);
c2c->direct = d;
ret = PICA_send_directc2c_switch(c2c);//??? who should send first?
if (ret != PICA_OK)
{
PICA_close_directc2c(d);
c2c->direct = NULL;
c2c->directc2c_state = PICA_DIRECTC2C_STATE_INACTIVE;
}
else
{
callbacks.direct_c2c_established_cb(c2c->peer_id, SSL_get_cipher_name(d->ssl));
c2c->directc2c_state = PICA_DIRECTC2C_STATE_ACTIVE;
}
}
else
{
fprintf(stderr, "directc2c: incoming connection from %s rejected: %s\n", addrstr,
c2c ? "the certificate is not the peer's" : "no connection is waiting for it");
PICA_close_directc2c(d);
}
/* pdprev stays put: d was spliced out above */
}
else
{
pdprev = &d->next;
}
d = dnext;
}
}
//process outgoing connections
c2c = c2n->chan_list_head;
while(c2c)
{
if (c2c->directc2c_state == PICA_DIRECTC2C_STATE_FAILEDTOCONNECT)
{
if (c2c->outgoing == PICA_C2C_OUTGOING && c2c->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING)
{
ret = PICA_send_directc2cfailed(c2c);
if (ret == PICA_OK)
c2c->directc2c_state = PICA_DIRECTC2C_STATE_WAITINGINCOMING;
else
c2c->directc2c_state = PICA_DIRECTC2C_STATE_INACTIVE;
}
else
c2c->directc2c_state = PICA_DIRECTC2C_STATE_INACTIVE;
}
if (c2c->directc2c_state == PICA_DIRECTC2C_STATE_CONNECTING)
{
char addrstr[PICA_DIRECTC2C_ADDRSTRSIZE];
d = c2c->direct;
ret = PICA_OK;
directc2c_addrstr(&d->addr, addrstr);
/* On to the next address, see PICA_DIRECTC2C_CONNECT_TIMEOUT -
* unless the socket has something for us: the event loop may
* not have run for a while, and a connection that has made it
* meanwhile is not a late one.
*/
if ((d->state == PICA_DIRECTC2C_CONNSTATE_CONNECTING || d->state == PICA_DIRECTC2C_CONNSTATE_WAITINGTLS)
&& PICA_media_now() >= d->attempt_deadline
&& !FD_ISSET(d->sck, wfds) && !FD_ISSET(d->sck, rfds))
{
fprintf(stderr, "directc2c: connection to %s failed: %s timed out after %u ms\n", addrstr,
d->state == PICA_DIRECTC2C_CONNSTATE_CONNECTING ? "TCP connection" : "TLS handshake",
(unsigned int)(PICA_media_now() - d->attempt_started));
d->state = PICA_DIRECTC2C_CONNSTATE_FAILED;
}
switch(d->state)
{
case PICA_DIRECTC2C_CONNSTATE_CONNECTING:
if (FD_ISSET(d->sck, wfds))
{
ret = check_async_connect_result(d->sck, (struct sockaddr*)&d->addr, sizeof(d->addr));
if (ret == PICA_OK)
{
fprintf(stderr, "directc2c: TCP connection to %s made in %u ms, TLS handshake\n", addrstr,
(unsigned int)(PICA_media_now() - d->attempt_started));
/* the TLS handshake gets the rest of the full timeout,
* also for a private address, see
* PICA_DIRECTC2C_LAN_CONNECT_TIMEOUT */
d->attempt_deadline = d->attempt_started + PICA_DIRECTC2C_CONNECT_TIMEOUT;
ret = directc2c_stage2_starttls(d, c2c);
if (ret != PICA_OK)
{
fprintf(stderr, "directc2c: connection to %s failed: TLS could not be started\n", addrstr);
d->state = PICA_DIRECTC2C_CONNSTATE_FAILED;
}
}
else
{
fprintf(stderr, "directc2c: connection to %s failed: TCP connection refused or unreachable\n",
addrstr);
d->state = PICA_DIRECTC2C_CONNSTATE_FAILED;
}
}
break;
case PICA_DIRECTC2C_CONNSTATE_WAITINGTLS:
if (FD_ISSET(d->sck, wfds) || FD_ISSET(d->sck, rfds))
{
ret = SSL_connect(d->ssl);
if (ret != 1)
{
ret = process_async_ssl_errors(d->ssl, ret, &d->want_write, 0);
if (ret != PICA_OK)
{
fprintf(stderr, "directc2c: connection to %s failed: TLS handshake failed\n", addrstr);
d->state = PICA_DIRECTC2C_CONNSTATE_FAILED;
}
break;
}
ret = directc2c_verify_peer_cert(d, c2c);
if (ret != PICA_OK)
{
fprintf(stderr, "directc2c: connection to %s failed: the certificate is not the peer's\n", addrstr);
d->state = PICA_DIRECTC2C_CONNSTATE_FAILED;
break;
}
ret = PICA_send_directc2c_switch(c2c);
if (ret != PICA_OK)
{
fprintf(stderr, "directc2c: connection to %s failed: could not send 0x0D\n", addrstr);
d->state = PICA_DIRECTC2C_CONNSTATE_FAILED;
break;
}
fprintf(stderr, "directc2c: connection to %s established in %u ms\n", addrstr,
(unsigned int)(PICA_media_now() - d->attempt_started));
d->state = PICA_DIRECTC2C_CONNSTATE_ACTIVE;
}
break;
case PICA_DIRECTC2C_CONNSTATE_FAILED:
ret = directc2c_connect_next(d, c2c);
if (ret == PICA_ERRNOTFOUND)
{
PICA_close_directc2c(d);
c2c->direct = 0;
c2c->directc2c_state = PICA_DIRECTC2C_STATE_FAILEDTOCONNECT;
}
break;
case PICA_DIRECTC2C_CONNSTATE_ACTIVE:
c2c->directc2c_state = PICA_DIRECTC2C_STATE_ACTIVE;
callbacks.direct_c2c_established_cb(c2c->peer_id, SSL_get_cipher_name(d->ssl));
break;
}
// if (ret != PICA_OK)
// {
// PICA_close_directc2c(d);
// c2c->direct = 0;
// if (c2c->directc2c_state != PICA_DIRECTC2C_STATE_FAILEDTOCONNECT)
// c2c->directc2c_state = PICA_DIRECTC2C_STATE_INACTIVE;//fallback to c2c through node?
// }
}
c2c = c2c->next;
}
}
static void listener_add_connection(struct PICA_listener *lst, SOCKET s, const struct sockaddr_in *peer_addr)
{
PICA_TRACEFUNC
struct PICA_directc2c *nc;
unsigned int count = 0;
int ret;
/* Bound the number of half-open incoming connections, so a peer cannot
* exhaust memory/descriptors by opening many and never finishing them.
*/
for (nc = lst->accepted_connections; nc; nc = nc->next)
if (++count >= PICA_DIRECTC2C_MAX_ACCEPTED)
{
CLOSE(s);
return;
}
nc = calloc(1, sizeof(struct PICA_directc2c));
if (!nc)
{
CLOSE(s);
return;
}
nc->is_outgoing = PICA_DIRECTC2C_INCOMING;
nc->sck = s;
/* Kept for the media connection: it is the only place the peer's address
* is known on this side, and datagrams arriving from anywhere else
* cannot belong to a call with this peer. The port number is the peer's
* outgoing TCP port and is not used.
*/
nc->addr = *peer_addr;
nc->ssl = SSL_new(lst->acc->ctx);
nc->state = PICA_DIRECTC2C_CONNSTATE_NEW;
nc->accepted_tmst = time(0);
if (!nc->ssl)
{
CLOSE(s);
free(nc);
return;
}
SSL_set_fd(nc->ssl, nc->sck);
SSL_set_verify(nc->ssl, SSL_VERIFY_PEER, PICA_verify_callback);
SSL_set_verify_depth(nc->ssl, 1);
ret = SSL_accept(nc->ssl);
if (ret <= 0)
{
/* Only a WANT_READ/WANT_WRITE means the handshake is merely unfinished;
* anything else is a real failure. Free the SSL object and close the
* socket on the failure path - dropping only the struct would leak both.
*/
if (!(ret < 0 && (SSL_get_error(nc->ssl, ret) == SSL_ERROR_WANT_READ
|| SSL_get_error(nc->ssl, ret) == SSL_ERROR_WANT_WRITE)))
{
SSL_free(nc->ssl);
CLOSE(nc->sck);
free(nc);
return;
}
}
nc->state = PICA_DIRECTC2C_CONNSTATE_WAITINGTLS;
nc->next = lst->accepted_connections;
lst->accepted_connections = nc;
}
static int process_listener_conn(struct PICA_directc2c *conn, fd_set *rfds, fd_set *wfds)
{
if (conn->peer_cert == NULL)
{
if (FD_ISSET(conn->sck, rfds) || FD_ISSET(conn->sck, wfds))
{
int ret;
ret = SSL_accept(conn->ssl);
if (ret == 1)
{
conn->peer_cert = SSL_get_peer_certificate(conn->ssl);
if (!conn->peer_cert)
return PICA_ERRSSL;
conn->state = PICA_DIRECTC2C_CONNSTATE_ACTIVE;
return PICA_OK;
}
if (ret == 0)
return PICA_ERRSSL;
if (ret < 0)
{
ret = SSL_get_error(conn->ssl, ret);
if (ret == SSL_ERROR_WANT_WRITE)
conn->want_write = 1;
if (ret != SSL_ERROR_WANT_READ && ret != SSL_ERROR_WANT_WRITE)
return PICA_ERRSSL;
}
}
}
return PICA_OK;
}
static int process_listener(struct PICA_listener *lst, fd_set *rfds, fd_set *wfds)
{
struct PICA_directc2c *conn;
struct PICA_directc2c **pprevconn;
if (FD_ISSET(lst->sck_listener, rfds))
{
SOCKET s;
struct sockaddr_in addr;
int addrsize = sizeof(struct sockaddr_in);
s = accept(lst->sck_listener, (struct sockaddr*)&addr, &addrsize);
if (s >= 0)
{
IOCTLSETNONBLOCKINGSOCKET(s, 1);
SETTCPNODELAY(s);
listener_add_connection(lst, s, &addr);
}
}
conn = lst->accepted_connections;
pprevconn = &lst->accepted_connections;
while(conn)
{
int ret;
struct PICA_directc2c *kill_ptr = NULL;
if ((ret = process_listener_conn(conn, rfds, wfds)) != PICA_OK)
{
kill_ptr = conn;
}
else if (conn->peer_cert == NULL
&& (time(0) - conn->accepted_tmst) > PICA_DIRECTC2C_ACCEPT_TIMEOUT)
{
/* peer_cert is set only once the handshake completes, so a NULL
* one past the timeout is a connection that never finished TLS.
*/
kill_ptr = conn;
}
if (!kill_ptr)
pprevconn = &conn->next;
conn = conn->next;
if (kill_ptr)
{
*pprevconn = kill_ptr->next;
PICA_close_directc2c(kill_ptr);
}
}
return PICA_OK;
}
static void fdset_add(fd_set *fds, int fd, int *max)
{
FD_SET(fd, fds);
if (fd > *max)
*max = fd;
}
int PICA_event_loop(struct PICA_c2n **connections, int timeout)
{
fd_set rfds, wfds;
struct timeval tv;
int ret, nfds = 0;
struct PICA_c2n **ic2n;
//puts("PICA_event_loop");//debug
tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000;
FD_ZERO(&rfds);
FD_ZERO(&wfds);
ic2n = connections;
while(ic2n && *ic2n)
{
struct PICA_c2c *ic2c;
struct PICA_directc2c *ilstcon;
//printf("event_loop: adding c2n %p\n", *ic2n);//debug
fdset_add(&rfds, (*ic2n)->sck_comm, &nfds);
if ((*ic2n)->write_pos || (*ic2n)->state == PICA_C2N_STATE_CONNECTING
|| (*ic2n)->want_write/*(*ic2n)->state == PICA_C2N_STATE_WAITINGTLS*/)
{
(*ic2n)->want_write = 0;
fdset_add(&wfds, (*ic2n)->sck_comm, &nfds);
}
if ((*ic2n)->directc2c_listener)
{
fdset_add(&rfds, (*ic2n)->directc2c_listener->sck_listener, &nfds);
ilstcon = (*ic2n)->directc2c_listener->accepted_connections;
while (ilstcon)
{
fdset_add(&rfds, ilstcon->sck, &nfds);
if (ilstcon->want_write)
fdset_add(&wfds, ilstcon->sck, &nfds);
ilstcon->want_write = 0;
ilstcon = ilstcon->next;
}
}
ic2c = (*ic2n)->chan_list_head;
while(ic2c)
{
if (ic2c->state >= PICA_C2C_STATE_CONNECTING)
{
fdset_add(&rfds, ic2c->sck_data, &nfds);
if ((ic2c->write_pos || ic2c->state == PICA_C2C_STATE_CONNECTING || (ic2c->state == PICA_C2C_STATE_WAITINGTLS && ic2c->want_write)
|| ic2c->sendfilestate == PICA_CHANSENDFILESTATE_SENDING) && ic2c->directc2c_state != PICA_DIRECTC2C_STATE_ACTIVE)
{
ic2c->want_write = 0;
fdset_add(&wfds, ic2c->sck_data, &nfds);
}
}
if (ic2c->state == PICA_C2C_STATE_ACTIVE && (ic2c->directc2c_state == PICA_DIRECTC2C_STATE_CONNECTING || ic2c->directc2c_state == PICA_DIRECTC2C_STATE_ACTIVE)
&& ic2c->direct && ic2c->direct->state >= PICA_DIRECTC2C_CONNSTATE_CONNECTING)
{
fdset_add(&rfds, ic2c->direct->sck, &nfds);
if (ic2c->write_pos || ic2c->direct->state == PICA_DIRECTC2C_CONNSTATE_CONNECTING || ic2c->direct->want_write || ic2c->sendfilestate == PICA_CHANSENDFILESTATE_SENDING)
{
ic2c->direct->want_write = 0;
fdset_add(&wfds, ic2c->direct->sck, &nfds);
}
}
ic2c = ic2c->next;
}
PICA_media_fdset(*ic2n, &rfds, &nfds);
ic2n++;
}
ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
if (ret == -1)
{
#ifndef WIN32
if (errno == EINTR)
return PICA_OK;
else
return PICA_ERRSOCK;
#else
#warning "implement handling of select() errors on Windows!"
#endif
}
//printf("select() returned %i\n", ret);//debug
//processing listeners, c2n and c2c connections
ic2n = connections;
while(ic2n && *ic2n)
{
struct PICA_c2c *ic2c;
//processing current c2n
ret = process_c2n(*ic2n, &rfds, &wfds);
if (ret != PICA_OK)
{
if ((*ic2n)->state == PICA_C2N_STATE_CONNECTED)
callbacks.c2n_closed_cb(*ic2n, ret);
else
callbacks.c2n_failed_cb(*ic2n, ret);
PICA_close_c2n(*ic2n);
}
else
{
struct PICA_c2c *kill_ptr = 0;
//processing listener associated with current c2n
if ((*ic2n)->directc2c_listener)
{
ret = process_listener((*ic2n)->directc2c_listener, &rfds, &wfds);
if (ret != PICA_OK)
{
callbacks.listener_error_cb((*ic2n)->directc2c_listener, ret);
PICA_close_listener((*ic2n)->directc2c_listener);
}
}
ic2c = (*ic2n)->chan_list_head;
//processing c2c connections associated with current c2n
while(ic2c)
{
ret = process_c2c(ic2c, &rfds, &wfds);
if (ret != PICA_OK)
kill_ptr = ic2c;
ic2c = ic2c->next;
if (kill_ptr)
{
PICA_close_c2c(kill_ptr);
kill_ptr = 0;
}
}
/* processing direct c2c connections associated with current c2n -
* even with them disabled now, those of c2c connections made
* before that */
process_directc2c(*ic2n, &rfds, &wfds);
//processing media connections of calls in progress
PICA_media_process(*ic2n, &rfds);
process_calls(*ic2n);
process_udpaddr(*ic2n);
}
ic2n++;
}
return PICA_OK;
}
int PICA_write_ssl(SSL *ssl, unsigned char *buf, unsigned int *ppos, unsigned int *btw)
{
int ret;
if (*ppos > 0 )
{
if (*btw == 0)
*btw = *ppos;
ret = SSL_write( ssl, buf, *btw);
if (ret > 0)
{
if (ret < *ppos)
memmove( buf, buf + ret, *ppos - ret);
*ppos -= ret;
*btw = 0;
}
if (ret < 0)
{
ret = SSL_get_error( ssl, ret);
if (! (ret == SSL_ERROR_WANT_WRITE || ret == SSL_ERROR_WANT_READ))
return PICA_ERRSSL;
}
if (ret == 0)
return PICA_ERRSERV;
}
return PICA_OK;
}
int PICA_write_c2n(struct PICA_c2n *ci)
{
int ret = PICA_ERRINVARG;
ret = PICA_write_ssl( ci->ssl_comm, ci->write_buf, &ci->write_pos, &ci->write_sslbytestowrite);
if (ci->disconnect_on_empty_write_buf)
PICA_close_c2n(ci);
return ret;
}
int PICA_write_c2c(struct PICA_c2c *chn)
{
int ret = PICA_ERRINVARG;
if (chn->state != PICA_C2C_STATE_ACTIVE && chn->state != PICA_C2C_STATE_CONNID
&& chn->state != PICA_C2C_STATE_WAITINGREP && chn->state != PICA_C2C_STATE_WAITINGC2CPROTOVER)
{
/* WAITINGC2CPROTOVER is a legitimate write state: the callee sends
* VERDIFFER from there on a protocol-version mismatch. Any state that
* really is unexpected closes this one channel - a library must not
* take the whole host process down over a peer-driven condition.
*/
fputs("PICA_write_c2c() was called in an incorrect state!\n", stderr);
return PICA_ERRSERV;
}
{
SSL *ssl_to_write = chn->ssl;
if (chn->switched_to_directc2c_write)
ssl_to_write = chn->direct->ssl;
if (chn->directc2c_write_barrier_pos)
{
if (chn->directc2c_write_before_barrier_pos == 0)
chn->directc2c_write_before_barrier_pos = chn->directc2c_write_barrier_pos;
ret = PICA_write_ssl(chn->ssl, chn->write_buf, &chn->directc2c_write_before_barrier_pos, &chn->write_sslbytestowrite);
if (ret == PICA_OK && chn->directc2c_write_before_barrier_pos == 0)
{
chn->switched_to_directc2c_write = 1;
memmove(chn->write_buf, chn->write_buf + chn->directc2c_write_barrier_pos, chn->write_pos - chn->directc2c_write_barrier_pos);
chn->write_pos -= chn->directc2c_write_barrier_pos;
chn->directc2c_write_barrier_pos = 0;
}
}
else
ret = PICA_write_ssl(ssl_to_write, chn->write_buf, &chn->write_pos, &chn->write_sslbytestowrite);
}
if (chn->disconnect_on_empty_write_buf && chn->write_pos == 0)
PICA_close_c2c(chn);
return ret;
}
int PICA_read_ssl(SSL *ssl, unsigned char *buf, unsigned int *ppos, unsigned int size)
{
int ret;
ret = SSL_read(ssl, buf + *ppos, size - *ppos);
if (!ret)
return PICA_ERRSSL;
if (ret < 0)
switch(SSL_get_error(ssl, ret))
{
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_READ:
break;
default:
return PICA_ERRSSL;
};
if (ret > 0)
{
*ppos += ret;
}
return PICA_OK;
}
int PICA_read_c2c(struct PICA_c2c *chn)
{
int ret;
SSL *ssl_to_read = chn->ssl;
if (chn->state != PICA_C2C_STATE_WAITINGREP && chn->state != PICA_C2C_STATE_WAITINGC2CPROTOVER && chn->state != PICA_C2C_STATE_ACTIVE)
{
/* Close this one channel rather than exit()-ing the host process. */
fputs("PICA_read_c2c() was called in an incorrect state!\n", stderr);
return PICA_ERRSERV;
}
if (chn->switched_to_directc2c_read)
ssl_to_read = chn->direct->ssl;
ret = PICA_read_ssl(ssl_to_read, chn->read_buf, &chn->read_pos, PICA_CHANREADBUFSIZE);
if (ret == PICA_OK)
{
const struct PICA_msginfo *msgs;
unsigned int nmsgs;
nmsgs = MSGINFO_MSGSNUM(c2c_messages);
msgs = c2c_messages;
if(!PICA_processdatastream(chn->read_buf, &(chn->read_pos ), chn, msgs, nmsgs))
return PICA_ERRSERV;
}
return ret;
}
int PICA_read_c2n(struct PICA_c2n *ci)
{
int ret;
ret = PICA_read_ssl(ci->ssl_comm, ci->read_buf, &ci->read_pos, PICA_CONNREADBUFSIZE);
if (ret == PICA_OK)
{
if(!PICA_processdatastream( ci->read_buf, &(ci->read_pos), ci, c2n_messages, MSGINFO_MSGSNUM(c2n_messages)))
return PICA_ERRSERV;
}
return ret;
}
struct PICA_proto_msg* c2n_writebuf_push(struct PICA_c2n *ci, unsigned int msgid, unsigned int size)
{
struct PICA_proto_msg *mp;
if (! ci->write_buf)
{
ci->write_buf = calloc(PICA_CONNWRITEBUFSIZE, 1);
if (!ci->write_buf)
return 0;
ci->write_buflen = PICA_CONNWRITEBUFSIZE;
}
if (ci->write_buflen - ci->write_pos < size)
{
unsigned char*p;
p = realloc(ci->write_buf, size + ci->write_pos);
if (p)
{
ci->write_buf = p;
ci->write_buflen = size + ci->write_pos;
}
else
return 0;
}
mp = (struct PICA_proto_msg *)(ci->write_buf + ci->write_pos);
mp->head[0] = mp->head[1] = msgid;
ci->write_pos += size;
return mp;
}
struct PICA_proto_msg* c2c_writebuf_push(struct PICA_c2c *chn, unsigned int msgid, unsigned int size)
{
struct PICA_proto_msg *mp;
if (! chn->write_buf)
{
chn->write_buf = calloc(PICA_CHANWRITEBUFSIZE, 1);
if (!chn->write_buf)
return 0;
chn->write_buflen = PICA_CHANWRITEBUFSIZE;
}
if (chn->write_buflen - chn->write_pos < size)
{
unsigned char*p;
p = realloc(chn->write_buf, size + chn->write_pos);
if (p)
{
chn->write_buf = p;
chn->write_buflen = size + chn->write_pos;
}
else
return 0;
}
mp = (struct PICA_proto_msg *)(chn->write_buf + chn->write_pos);
mp->head[0] = mp->head[1] = msgid;
chn->write_pos += size;
return mp;
}
/* Adds an address to a list under construction, unless it is in it already
* - an interface address that is public is what UPnP reports too, when the
* IGD runs on this very machine.
*/
static void addrlist_add(struct PICA_listener_addr *list, int *count, in_addr_t addr, uint16_t port)
{
int i;
if (addr == INADDR_ANY || port == 0 || *count >= PICA_DIRECTC2C_MAX_ADDRS)
return;
for (i = 0; i < *count; i++)
if (list[i].addr == addr && list[i].port == port)
return;
list[*count].addr = addr;
list[*count].port = port;
list[*count].is_upnp = 0;
(*count)++;
}
/* The addresses to announce in 0x0B, see the description of the message:
* private ones first, then public ones. Built when it is sent rather than
* once, since interfaces come and go - a VPN connected, a laptop moved to
* another network.
*/
static int listener_addrlist(const struct PICA_listener *l, struct PICA_listener_addr *list)
{
int count = 0;
int i;
if (l->addrs_manual)
{
for (i = 0; i < l->addrs_count; i++)
{
if (l->addrs[i].is_upnp)
addrlist_add(list, &count, l->upnp_addr, l->upnp_port);
else
addrlist_add(list, &count, l->addrs[i].addr, l->addrs[i].port);
}
}
else
{
in_addr_t ifaddrs[PICA_IFADDRS_MAX];
int n;
n = PICA_get_ifaddrs_ipv4(ifaddrs, PICA_IFADDRS_MAX);
for (i = 0; i < n; i++)
addrlist_add(list, &count, ifaddrs[i], htons((uint16_t)l->local_port));
addrlist_add(list, &count, l->upnp_addr, l->upnp_port);
}
return count;
}
int PICA_send_directc2caddrlist(struct PICA_c2c *chn)
{
PICA_TRACEFUNC
if (chn->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING && chn->conn->directc2c_listener)
{
struct PICA_proto_msg *mp;
struct PICA_listener_addr list[PICA_DIRECTC2C_MAX_ADDRS];
int count, i;
unsigned int len;
unsigned char *p;
count = listener_addrlist(chn->conn->directc2c_listener, list);
/* nothing a peer could connect to */
if (count == 0)
return PICA_OK;
len = count * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_DIRECTC2C_ADDRLIST, len + 4)))
{
mp->tail[0] = len & 0xFF;
mp->tail[1] = (len >> 8) & 0xFF;
p = mp->tail + 2;
for (i = 0; i < count; i++)
{
*p++ = PICA_PROTO_DIRECTC2C_IPV4;
memcpy(p, &list[i].addr, 4);
memcpy(p + 4, &list[i].port, 2);
p += 6;
}
chn->directc2c_state = PICA_DIRECTC2C_STATE_WAITINGINCOMING;
}
}
return PICA_OK;
}
static int PICA_send_directc2cfailed(struct PICA_c2c *chn)
{
PICA_TRACEFUNC
struct PICA_proto_msg *mp;
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_DIRECTC2C_FAILED, PICA_PROTO_DIRECTC2C_FAILED_SIZE)))
{
RAND_pseudo_bytes(mp->tail, 2);
}
else
return PICA_ERRNOMEM;
return PICA_OK;
}
static int PICA_send_directc2c_switch(struct PICA_c2c *chn)
{
PICA_TRACEFUNC
struct PICA_proto_msg *mp;
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_DIRECTC2C_SWITCH, PICA_PROTO_DIRECTC2C_SWITCH_SIZE)))
{
RAND_pseudo_bytes(mp->tail, 2);
}
else
return PICA_ERRNOMEM;
chn->directc2c_write_barrier_pos = chn->write_pos;
return PICA_OK;
}
int PICA_send_msg(struct PICA_c2c *chn, char *buf, unsigned int len)
{
struct PICA_proto_msg *mp;
if (len > PICA_PROTO_C2CMSG_MAXDATASIZE)
return PICA_ERRMSGSIZE;
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_MSGUTF8, len + 4)))
{
*((uint16_t*)mp->tail) = len;
memcpy(mp->tail + 2, buf, len);
}
else
return PICA_ERRNOMEM;
return PICA_OK;
}
int PICA_send_file(struct PICA_c2c *chn, const char *filepath)
{
struct PICA_proto_msg *mp;
size_t namelen;
uint64_t file_size;
int ret;
const char *filename;//file name part of the filepath
if (chn->sendfilestate != PICA_CHANSENDFILESTATE_IDLE)
return PICA_ERRFILETRANSFERINPROGRESS;
if (filepath == NULL)
return PICA_ERRINVFILENAME;
#ifndef WIN32
filename = strrchr(filepath, '/');
#else
filename = strrchr(filepath, '\\');
#endif
if (filename)
filename++;
else
filename = filepath;
namelen = strlen(filename);
if (namelen == 0 || namelen > PICA_PROTO_C2CMSG_MAXFILENAMESIZE)
return PICA_ERRINVFILENAME;
if ((ret = PICA_sendfile_open_read(chn, filepath, &file_size)) != PICA_OK)
return ret;
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_SENDFILEREQUEST, namelen + 12)))
{
*((uint16_t*)mp->tail) = namelen + 8;
*((uint64_t*)(mp->tail + 2)) = file_size;
memcpy(mp->tail + 10, filename, namelen);
}
else
return PICA_ERRNOMEM;
chn->sendfilestate = PICA_CHANSENDFILESTATE_SENTREQ;
chn->sendfile_size = file_size;
chn->sendfile_pos = 0;
return PICA_OK;
}
int PICA_pause_file(struct PICA_c2c *chan, int sending)
{
int senderctl = PICA_PROTO_FILECONTROL_VOID;
int receiverctl = PICA_PROTO_FILECONTROL_VOID;
if (sending)
{
if (chan->sendfilestate != PICA_CHANSENDFILESTATE_SENDING)
return PICA_ERRINVARG;
chan->sendfilestate = PICA_CHANSENDFILESTATE_PAUSED;
senderctl = PICA_PROTO_FILECONTROL_PAUSE;
}
else
{
if (chan->recvfilestate != PICA_CHANRECVFILESTATE_RECEIVING)
return PICA_ERRINVARG;
chan->recvfilestate = PICA_CHANRECVFILESTATE_PAUSED;
receiverctl = PICA_PROTO_FILECONTROL_PAUSE;
}
return PICA_send_filecontrol(chan, senderctl, receiverctl);
}
int PICA_resume_file(struct PICA_c2c *chan, int sending)
{
int senderctl = PICA_PROTO_FILECONTROL_VOID;
int receiverctl = PICA_PROTO_FILECONTROL_VOID;
if (sending)
{
if (chan->sendfilestate != PICA_CHANSENDFILESTATE_PAUSED)
return PICA_ERRINVARG;
chan->sendfilestate = PICA_CHANSENDFILESTATE_SENDING;
senderctl = PICA_PROTO_FILECONTROL_RESUME;
}
else
{
if (chan->recvfilestate != PICA_CHANRECVFILESTATE_PAUSED)
return PICA_ERRINVARG;
chan->recvfilestate = PICA_CHANRECVFILESTATE_RECEIVING;
receiverctl = PICA_PROTO_FILECONTROL_RESUME;
}
return PICA_send_filecontrol(chan, senderctl, receiverctl);
}
int PICA_cancel_file(struct PICA_c2c *chan, int sending)
{
int senderctl = PICA_PROTO_FILECONTROL_VOID;
int receiverctl = PICA_PROTO_FILECONTROL_VOID;
if (sending)
{
if (chan->sendfilestate != PICA_CHANSENDFILESTATE_SENDING
&& chan->sendfilestate != PICA_CHANSENDFILESTATE_PAUSED)
return PICA_ERRINVARG;
fclose(chan->sendfile_stream);
chan->sendfile_stream = NULL;
chan->sendfilestate = PICA_CHANSENDFILESTATE_IDLE;
senderctl = PICA_PROTO_FILECONTROL_CANCEL;
}
else
{
if (chan->recvfilestate != PICA_CHANRECVFILESTATE_RECEIVING
&& chan->recvfilestate != PICA_CHANRECVFILESTATE_PAUSED)
return PICA_ERRINVARG;
fclose(chan->recvfile_stream);
chan->recvfile_stream = NULL;
chan->recvfilestate = PICA_CHANRECVFILESTATE_IDLE;
receiverctl = PICA_PROTO_FILECONTROL_CANCEL;
}
return PICA_send_filecontrol(chan, senderctl, receiverctl);
}
int PICA_send_filecontrol(struct PICA_c2c *chan, int senderctl, int receiverctl)
{
struct PICA_proto_msg *mp;
if ((mp = c2c_writebuf_push(chan, PICA_PROTO_FILECONTROL, PICA_PROTO_FILECONTROL_SIZE)))
{
mp->tail[0] = senderctl; //sender's command
mp->tail[1] = receiverctl; //receiver's command
}
else
return PICA_ERRNOMEM;
return PICA_OK;
}
int PICA_send_file_fragment(struct PICA_c2c *chn)
{
struct PICA_proto_msg *mp;
char buf[PICA_FILEFRAGMENTSIZE];
size_t fragment_size;
if (chn->sendfilestate != PICA_CHANSENDFILESTATE_SENDING)
return PICA_ERRFILETRANSFERNOTINPROGRESS;
fragment_size = fread(buf, 1, PICA_FILEFRAGMENTSIZE - 4, chn->sendfile_stream);
if (fragment_size == 0)
{
fclose(chn->sendfile_stream);
chn->sendfile_stream = NULL;
chn->sendfilestate = PICA_CHANSENDFILESTATE_IDLE;
PICA_send_filecontrol(chn, PICA_PROTO_FILECONTROL_IOERROR, PICA_PROTO_FILECONTROL_VOID);
return PICA_ERRFILEIO;
}
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_FILEFRAGMENT, fragment_size + 4)))
{
*((uint16_t*)mp->tail) = fragment_size;
memcpy(mp->tail + 2, buf, fragment_size);
}
else
{
return PICA_ERRNOMEM;
}
chn->sendfile_pos += fragment_size;
callbacks.file_progress_cb(chn->peer_id, chn->sendfile_pos, 0);
if (chn->sendfile_pos >= chn->sendfile_size)
{
chn->sendfilestate = PICA_CHANSENDFILESTATE_IDLE;
fclose(chn->sendfile_stream);
chn->sendfile_stream = NULL;
callbacks.file_finished_cb(chn->peer_id, 1);
}
if (chn->sendfile_pos > chn->sendfile_size)
return PICA_ERRFILEFRAGMENTCROSSEDSIZE;
return PICA_OK;
}
int PICA_start_call(struct PICA_c2c *chn, uint16_t width, uint16_t height)
{
int ret;
if (chn->call_state != PICA_CALL_STATE_IDLE)
return PICA_ERRCALLINPROGRESS;
ret = PICA_media_call_prepare(chn, 1, NULL, 0);
if (ret != PICA_OK)
return ret;
chn->media_call->recommended_width = width;
chn->media_call->recommended_height = height;
chn->call_state = PICA_CALL_STATE_CALLING;
/* 0x70 carries the address the node sees the call socket at, so it
* waits for the node's answer - normally one round trip - for a limited
* time, see process_calls()
*/
chn->media_call->pending_deadline = PICA_media_now() + PICA_MEDIA_LEARN_TIMEOUT;
if (!PICA_media_call_ready(chn))
{
chn->media_call->pending_msg = PICA_PROTO_CALLREQ;
return PICA_OK;
}
ret = call_send_info(chn, PICA_PROTO_CALLREQ);
if (ret != PICA_OK)
call_release(chn);
return ret;
}
int PICA_pickup_call(struct PICA_c2c *chn, uint16_t width, uint16_t height)
{
int ret;
if (chn->call_state != PICA_CALL_STATE_INCOMINGCALL)
return PICA_ERRCALLNOTINPROGRESS;
/* The address of the call socket has been asked for since the call
* started ringing and is usually known by now. If it is not, 0x71 waits
* for it a little longer; the call counts as answered for the user
* meanwhile.
*/
if (chn->media_call)
{
chn->media_call->recommended_width = width;
chn->media_call->recommended_height = height;
chn->media_call->pending_deadline = PICA_media_now() + PICA_MEDIA_LEARN_TIMEOUT;
}
if (!PICA_media_call_ready(chn))
{
chn->media_call->pending_msg = PICA_PROTO_CALLANS;
chn->call_state = PICA_CALL_STATE_ANSWERING;
return PICA_OK;
}
ret = call_answered(chn);
return ret;
}
int PICA_reject_call(struct PICA_c2c *chn)
{
struct PICA_proto_msg *mp;
if (chn->call_state != PICA_CALL_STATE_INCOMINGCALL)
return PICA_ERRCALLNOTINPROGRESS;
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALLREJ, PICA_PROTO_CALLREJ_SIZE)))
{
RAND_pseudo_bytes(mp->tail, 2);
}
else
{
return PICA_ERRNOMEM;
}
call_release(chn);
return PICA_OK;
}
int PICA_hangup_call(struct PICA_c2c *chn)
{
struct PICA_proto_msg *mp;
if (chn->call_state == PICA_CALL_STATE_IDLE)
return PICA_ERRCALLNOTINPROGRESS;
/* A call whose 0x70 is still waiting to be sent does not exist for the
* peer yet, and a 0x73 would be a protocol error to it.
*/
if (chn->call_state == PICA_CALL_STATE_CALLING && chn->media_call
&& chn->media_call->pending_msg == PICA_PROTO_CALLREQ)
{
call_release(chn);
return PICA_OK;
}
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALLFIN, PICA_PROTO_CALLFIN_SIZE)))
{
RAND_pseudo_bytes(mp->tail, 2);
}
else
{
return PICA_ERRNOMEM;
}
// handle incoming last stream packets?
call_release(chn);
return PICA_OK;
}
static int call_send_audio_params(struct PICA_c2c *chn, const char *codec_name, uint16_t sample_rate)
{
struct PICA_proto_msg *mp;
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALL_AUDIOPARAM, PICA_PROTO_CALL_AUDIOPARAM_SIZE)))
{
strncpy(mp->tail, codec_name, PICA_PROTO_CALL_CODECNAMESIZE);
*((uint16_t*)(mp->tail + PICA_PROTO_CALL_CODECNAMESIZE)) = sample_rate;
}
else
{
return PICA_ERRNOMEM;
}
return PICA_OK;
}
int PICA_set_call_audio_params(struct PICA_c2c *chn, const char *codec_name, uint16_t sample_rate)
{
struct PICA_media_call *mc = chn->media_call;
/* kept until 0x71 is out, see call_answered() */
if (chn->call_state == PICA_CALL_STATE_ANSWERING && mc)
{
snprintf(mc->audio_codec, sizeof(mc->audio_codec), "%s", codec_name);
mc->audio_sample_rate = sample_rate;
mc->audio_params_pending = 1;
return PICA_OK;
}
if (chn->call_state != PICA_CALL_STATE_ACTIVE)
return PICA_ERRCALLNOTINPROGRESS;
return call_send_audio_params(chn, codec_name, sample_rate);
}
static int call_send_video_params(struct PICA_c2c *chn, const char *codec_name, uint16_t width, uint16_t height)
{
struct PICA_proto_msg *mp;
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALL_VIDEOPARAM, PICA_PROTO_CALL_VIDEOPARAM_SIZE)))
{
strncpy(mp->tail, codec_name, PICA_PROTO_CALL_CODECNAMESIZE);
*((uint16_t*)(mp->tail + PICA_PROTO_CALL_CODECNAMESIZE)) = width;
*((uint16_t*)(mp->tail + PICA_PROTO_CALL_CODECNAMESIZE + sizeof(width))) = height;
}
else
{
return PICA_ERRNOMEM;
}
return PICA_OK;
}
int PICA_set_call_video_params(struct PICA_c2c *chn, const char *codec_name, uint16_t width, uint16_t height)
{
struct PICA_media_call *mc = chn->media_call;
if (chn->call_state == PICA_CALL_STATE_ANSWERING && mc)
{
snprintf(mc->video_codec, sizeof(mc->video_codec), "%s", codec_name);
mc->video_width = width;
mc->video_height = height;
mc->video_params_pending = 1;
return PICA_OK;
}
if (chn->call_state != PICA_CALL_STATE_ACTIVE)
return PICA_ERRCALLNOTINPROGRESS;
return call_send_video_params(chn, codec_name, width, height);
}
static int PICA_send_call_packet(struct PICA_c2c *chn, unsigned int msgid, uint16_t seq_num,
uint32_t timestamp, const char *buf, unsigned int len)
{
struct PICA_proto_msg *mp;
if (chn->call_state != PICA_CALL_STATE_ACTIVE)
return PICA_ERRCALLNOTINPROGRESS;
if (len > PICA_media_max_payload(chn))
return PICA_ERRMSGSIZE;
if (PICA_media_is_active(chn))
{
/* Written to the socket here and now instead of being appended to
* the write buffer the event loop drains: a datagram never blocks
* for long, and waiting for the next pass of the event loop would
* add more delay to every packet than the rest of the call path
* costs together.
*/
unsigned char pkt[PICA_MEDIA_LINK_MTU];
unsigned int pktlen = 4 + PICA_PROTO_CALL_PACKET_HDRSIZE + len;
if (pktlen > sizeof(pkt))
return PICA_ERRMSGSIZE;
pkt[0] = pkt[1] = msgid;
*((uint16_t*)(pkt + 2)) = len + PICA_PROTO_CALL_PACKET_HDRSIZE;
*((uint16_t*)(pkt + 4)) = seq_num;
*((uint32_t*)(pkt + 4 + PICA_PROTO_CALL_PACKET_SEQNUM_SIZE)) = timestamp;
memcpy(pkt + 4 + PICA_PROTO_CALL_PACKET_HDRSIZE, buf, len);
return PICA_media_send(chn, pkt, pktlen);
}
if ((mp = c2c_writebuf_push(chn, msgid, len + 4 + PICA_PROTO_CALL_PACKET_HDRSIZE)))
{
*((uint16_t*)mp->tail) = len + PICA_PROTO_CALL_PACKET_HDRSIZE;
*((uint16_t*)(mp->tail + 2)) = seq_num;
*((uint32_t*)(mp->tail + 2 + PICA_PROTO_CALL_PACKET_SEQNUM_SIZE)) = timestamp;
memcpy(mp->tail + 2 + PICA_PROTO_CALL_PACKET_HDRSIZE, buf, len);
}
else
{
return PICA_ERRNOMEM;
}
return PICA_OK;
}
int PICA_send_audio_packet(struct PICA_c2c *chn, uint16_t seq_num, uint32_t timestamp, const char *buf, unsigned int len)
{
return PICA_send_call_packet(chn, PICA_PROTO_CALL_AUDIO_PACKET, seq_num, timestamp, buf, len);
}
int PICA_send_video_packet(struct PICA_c2c *chn, uint16_t seq_num, uint32_t timestamp, const char *buf, unsigned int len)
{
return PICA_send_call_packet(chn, PICA_PROTO_CALL_VIDEO_PACKET, seq_num, timestamp, buf, len);
}
void PICA_close_directc2c(struct PICA_directc2c *d)
{
PICA_TRACEFUNC
if (d->peer_cert)
X509_free(d->peer_cert);
if (d->addrlist)
free(d->addrlist);
SSL_free(d->ssl);
SHUTDOWN(d->sck);
CLOSE(d->sck);
d->next = NULL;
free(d);
}
void PICA_close_c2c(struct PICA_c2c *chn)
{
struct PICA_c2c *ipt;
PICA_TRACEFUNC
ipt = chn->conn->chan_list_head;
//puts("PICA_close_c2c_chkp0");//debug
while(ipt)
{
if (ipt == chn)
{
if (ipt->next)
ipt->next->prev = ipt->prev;
else
chn->conn->chan_list_end = ipt->prev;
if (ipt->prev)
ipt->prev->next = ipt->next;
else
chn->conn->chan_list_head = ipt->next;
break;
}
ipt = ipt->next;
}
//puts("PICA_close_c2c_chkp1");//debug
PICA_media_close(chn);
PICA_media_call_free(chn);
if (chn -> sendfile_stream)
fclose(chn -> sendfile_stream);
if (chn -> recvfile_stream)
fclose(chn -> recvfile_stream);
if (chn -> read_buf)
free(chn -> read_buf);
if (chn -> write_buf)
free(chn -> write_buf);
if (chn->peer_cert)
X509_free(chn->peer_cert);
//puts("PICA_close_c2c_chkp2");//debug
if (chn->ssl)
SSL_shutdown(chn->ssl);
//puts("PICA_close_c2c_chkp3");//debug
if (chn->ssl)
{
//printf("3 SSL_free(%X)\n",chn->ssl);//debug
SSL_free(chn->ssl);
}
//puts("PICA_close_c2c_chkp4");//debug
SHUTDOWN(chn->sck_data);
//puts("PICA_close_c2c_chkp5");//debug
CLOSE(chn->sck_data);
//puts("PICA_close_c2c_chkp6");//debug
if (chn->direct)
PICA_close_directc2c(chn->direct);
free(chn);
//puts("PICA_close_c2c_chkp7");//debug
}
void PICA_close_c2n(struct PICA_c2n *cid)
{
PICA_TRACEFUNC
struct PICA_c2c *ipt;
while((ipt = cid->chan_list_head))
PICA_close_c2c(ipt);
SSL_shutdown(cid->ssl_comm);
//printf("4 SSL_free(%X)\n",cid->ssl_comm);//debug
SSL_free(cid->ssl_comm);
SHUTDOWN(cid->sck_comm);
CLOSE(cid->sck_comm);
free(cid->read_buf);
if (cid->write_buf)
free(cid->write_buf);
free(cid);
}
void PICA_close_acc(struct PICA_acc *a)
{
SSL_CTX_free(a->ctx);
free(a->pkey_file);
free(a->cert_file);
free(a);
}
void PICA_close_listener(struct PICA_listener *l)
{
CLOSE(l->sck_listener);
if (l->media)
PICA_media_listener_close(l->media);
while(l->accepted_connections)
{
struct PICA_directc2c *c = l->accepted_connections;
l->accepted_connections = c->next;
PICA_close_directc2c(c);
}
free(l);
}
#ifdef WIN32
const char *PICA_inet_ntop(int af, const void *src, char *dst, size_t size)
{
unsigned char *chsrc = (unsigned char*)src;
switch(af)
{
case AF_INET:
sprintf(dst, "%u.%u.%u.%u", chsrc[0], chsrc[1], chsrc[2], chsrc[3]);
break;
case AF_INET6:
sprintf(dst, "%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x", chsrc[0], chsrc[1], chsrc[2], chsrc[3],
chsrc[4], chsrc[5], chsrc[6], chsrc[7],
chsrc[8], chsrc[9], chsrc[10], chsrc[11],
chsrc[12], chsrc[13], chsrc[14], chsrc[15]);
break;
default:
return NULL;
}
return dst;
}
#endif
int PICA_sendfile_open_read(struct PICA_c2c *chn, const char *filename_utf8, uint64_t *file_size)
{
#ifdef WIN32
{
wchar_t *wfilename = NULL;
int wlen;
wlen = MultiByteToWideChar(CP_UTF8, 0, filename_utf8, -1, NULL, 0);
if (wlen == 0 || wlen == 0xFFFD)
return PICA_ERRINVFILENAME;
wfilename = (wchar_t*)malloc(wlen * sizeof(wchar_t));
if (!wfilename)
return PICA_ERRNOMEM;
MultiByteToWideChar(CP_UTF8, 0, filename_utf8, -1, wfilename, wlen);
chn->sendfile_stream = _wfopen(wfilename, L"rb");
free(wfilename);
if (chn->sendfile_stream == NULL)
return PICA_ERRFILEOPEN;
if (_fseeki64(chn->sendfile_stream, 0, SEEK_END) != 0)
return PICA_ERRFILEOPEN;
*file_size = _ftelli64(chn->sendfile_stream);
if (_fseeki64(chn->sendfile_stream, 0, SEEK_SET) != 0)
return PICA_ERRFILEOPEN;
}
#else
chn->sendfile_stream = fopen(filename_utf8, "rb");
if (chn->sendfile_stream == NULL)
return PICA_ERRFILEOPEN;
if (fseeko(chn->sendfile_stream, 0, SEEK_END) != 0)
return PICA_ERRFILEOPEN;
*file_size = ftello(chn->sendfile_stream);
if (fseeko(chn->sendfile_stream, 0, SEEK_SET) != 0)
return PICA_ERRFILEOPEN;
#endif
return PICA_OK;
}
int PICA_recvfile_open_write(struct PICA_c2c *chn, const char *filename_utf8, unsigned int filenamesize)
{
/////////////
#ifdef WIN32
{
wchar_t *rfilename = NULL;
int rlen;
rlen = MultiByteToWideChar(CP_UTF8, 0, filename_utf8, filenamesize, NULL, 0);
if (rlen == 0 || rlen == 0xFFFD)
return PICA_ERRINVFILENAME;
rlen++;//space for terminating zero character
rfilename = malloc(rlen * sizeof(wchar_t));
if (!rfilename)
return PICA_ERRNOMEM;
MultiByteToWideChar(CP_UTF8, 0, filename_utf8, filenamesize, rfilename, rlen);
rfilename[rlen - 1] = L'\0';
chn->recvfile_stream = _wfopen(rfilename, L"wb");
free(rfilename);
if (chn->recvfile_stream == NULL)
return PICA_ERRFILEOPEN;
}
#else
char *filename = malloc(filenamesize + 1);
memcpy(filename, filename_utf8, filenamesize);
filename[filenamesize] = '\0';
chn->recvfile_stream = fopen(filename, "wb");
free(filename);
if (chn->recvfile_stream == NULL)
return PICA_ERRFILEOPEN;
#endif
/////////////
return PICA_OK;
}
|