summaryrefslogtreecommitdiffstats
path: root/PICA_node.c
blob: 9602380e2f0ea539ab32ab3398185f4152e0b4a6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
//Программа является узлом сети 
//
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>

#include "PICA_node.h"
#include "PICA_proto.h"
#include "PICA_msgproc.h"
#include "PICA_nodeaddrlist.h"
#include "PICA_common.h"
#include "PICA_nodejoinskynet.h"
#include "PICA_nodeconfig.h"

#ifdef NO_RAND_DEV
#include "PICA_rand_seed.h"
#endif

#define MAX_NEWCONNS 64

#define NEWCONN_TIMEOUT 10 //sec
#define JOINSKYNET_TIMEOUT 15
#define SELECT_TIMEOUT 1

clock_t TMO_CCLINK_WAITACTIVE=15;//CONF //таймаут ожидания перехода соединения в активное состояние

char *my_addr;//TEMP CONF FIXME  собственный ip-адрес узла, на котором он ожидает соединения

SOCKET listen_comm_sck;//*

SSL_CTX* ctx;
struct newconn newconns[MAX_NEWCONNS];
unsigned int newconns_pos=0;


struct client *client_tree_root;//корень дерева клиентов
struct client *client_list_head;//указатель на первый элемент списка клиентов или 0, если список пуст
struct client *client_list_end;//указатель на последний элемент списка клиентов или 0, если список пуст

struct cclink *cclink_list_head;
struct cclink *cclink_list_end;

unsigned int cclink_list_count;

struct nodelink *nodelink_list_head;
struct nodelink *nodelink_list_end;
unsigned int nodelink_list_count;

struct PICA_nodeaddr *nodeaddr_list_head;
struct PICA_nodeaddr *nodeaddr_list_end;
unsigned int nodeaddr_list_count;


char msg_VERDIFFER[4]={PICA_PROTO_VERDIFFER,PICA_PROTO_VERDIFFER,PICA_PROTO_VER_HIGH,PICA_PROTO_VER_LOW};
const unsigned int msg_VERDIFFER_len=4;

unsigned int procmsg_INITREQ(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_CONNID(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_NODECONNREQ(unsigned char* buf,unsigned int size,void* ptr);

unsigned int procmsg_CONNREQOUTG(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_CONNALLOW(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_CONNDENY(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_NODERESP(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_NEWNODE(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_NODELISTREQ(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_NODELIST(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_N2NFOUND(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_SEARCH(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_N2NCONNREQOUTG(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_N2NALLOW(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_N2NNOTFOUND(unsigned char* buf,unsigned int size,void* ptr);
unsigned int procmsg_N2NMSG(unsigned char* buf,unsigned int size,void* ptr);

struct cclink* cclink_list_add(struct client *clr,struct client *cle);
struct cclink* cclink_list_search(unsigned int caller_id, unsigned int callee_id);
struct cclink* cclink_list_findwaitsearch(unsigned int callee_id);
void cclink_list_addlocal(struct client *clr,struct client *cle);
void cclink_list_delete(struct cclink *l);
void cclink_list_addn2nclr(struct client *clr,unsigned int callee_id);
void cclink_setwaitconn(struct cclink *ccl);
void cclink_list_addn2ncle(unsigned int caller_id, struct nodelink *caller_node, struct client *cle);
void cclink_activate(struct cclink *ccl,SOCKET s);
void cclink_attach_remotecle_node(struct cclink *ccl, struct nodelink *callee_node);

struct client* client_tree_search(unsigned int id);//
struct client *client_list_addnew(struct newconn *nc);
struct PICA_proto_msg* client_wbuf_push(struct client *c,unsigned int msgid,unsigned int size);

struct PICA_proto_msg* nodelink_wbuf_push(struct nodelink *nl,unsigned int msgid,unsigned int size);
int nodelink_rbuf_grow(struct nodelink *nl);
int nodelink_attach_nodeaddr(struct nodelink *nl, unsigned int addr_type, void* nodeaddr, unsigned int nodeaddr_size);
struct nodelink *nodelink_list_addnew(struct newconn *nc);
void nodelink_list_delete(struct nodelink *n);

void newconn_close(struct newconn* nc);
void newconn_free(struct newconn* nc);
struct newconn* newconn_add(struct newconn *ncs,int *pos);

//описание формата сообщений, которые могут приходить _ОТ_ клиентов по управляющему защищенному соединению 
#define MSGINFO_MSGSNUM(arr) (sizeof(arr)/sizeof(struct PICA_msginfo))

struct PICA_msginfo  _msginfo_comm[]={
{PICA_PROTO_CONNREQOUTG, PICA_MSG_FIXED_SIZE, PICA_PROTO_CONNREQOUTG_SIZE, procmsg_CONNREQOUTG},
{PICA_PROTO_CONNALLOW, PICA_MSG_FIXED_SIZE, PICA_PROTO_CONNALLOW_SIZE, procmsg_CONNALLOW}, 
{PICA_PROTO_CONNDENY, PICA_MSG_FIXED_SIZE, PICA_PROTO_CONNDENY_SIZE, procmsg_CONNDENY},
{PICA_PROTO_CLNODELISTREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_CLNODELISTREQ_SIZE, procmsg_NODELISTREQ}
};//---!!! PING!!!

struct PICA_msginfo _msginfo_node[]={
{PICA_PROTO_INITRESPOK,PICA_MSG_FIXED_SIZE,PICA_PROTO_INITRESPOK_SIZE,procmsg_NODERESP},
{PICA_PROTO_VERDIFFER ,PICA_MSG_FIXED_SIZE,PICA_PROTO_VERDIFFER_SIZE,procmsg_NODERESP},
{PICA_PROTO_NEWNODE_IPV4 ,PICA_MSG_FIXED_SIZE,PICA_PROTO_NEWNODE_IPV4_SIZE,procmsg_NEWNODE},
{PICA_PROTO_NODELISTREQ,PICA_MSG_FIXED_SIZE,PICA_PROTO_NODELISTREQ_SIZE,procmsg_NODELISTREQ},
{PICA_PROTO_NODELIST,PICA_MSG_VAR_SIZE,PICA_MSG_VARSIZE_INT16,procmsg_NODELIST},

{PICA_PROTO_SEARCH,PICA_MSG_FIXED_SIZE,PICA_PROTO_SEARCH_SIZE,procmsg_SEARCH},
{PICA_PROTO_N2NFOUND,PICA_MSG_FIXED_SIZE,PICA_PROTO_N2NFOUND_SIZE,procmsg_N2NFOUND},
{PICA_PROTO_N2NFOUNDCACHE,PICA_MSG_VAR_SIZE,PICA_MSG_VARSIZE_INT16,procmsg_N2NFOUND},
{PICA_PROTO_N2NCONNREQOUTG,PICA_MSG_FIXED_SIZE,PICA_PROTO_N2NCONNREQOUTG_SIZE,procmsg_N2NCONNREQOUTG},
{PICA_PROTO_N2NALLOW,PICA_MSG_FIXED_SIZE,PICA_PROTO_N2NALLOW_SIZE,procmsg_N2NALLOW},
{PICA_PROTO_N2NNOTFOUND,PICA_MSG_FIXED_SIZE,PICA_PROTO_N2NNOTFOUND_SIZE,procmsg_N2NNOTFOUND},
{PICA_PROTO_N2NMSG,PICA_MSG_VAR_SIZE,PICA_MSG_VARSIZE_INT16,procmsg_N2NMSG}
};

struct PICA_msginfo _msginfo_newconn[]={
{PICA_PROTO_INITREQ,PICA_MSG_FIXED_SIZE,PICA_PROTO_INITREQ_SIZE,procmsg_INITREQ},
{PICA_PROTO_CONNID,PICA_MSG_FIXED_SIZE,PICA_PROTO_CONNID_SIZE,procmsg_CONNID},
{PICA_PROTO_NODECONNREQ,PICA_MSG_FIXED_SIZE,PICA_PROTO_NODECONNREQ_SIZE,procmsg_NODECONNREQ}
};



unsigned int procmsg_INITREQ(unsigned char* buf,unsigned int size,void* ptr)
{
struct newconn *nc=(struct newconn*)ptr;
struct PICA_proto_msg *mp;

if (buf[2]==PICA_PROTO_VER_HIGH && buf[3]==PICA_PROTO_VER_LOW)
	{
	struct client *c;
	c=client_list_addnew(nc);
	if (!c)
		return 0;
	
	newconn_free(nc);

	if (mp=client_wbuf_push(c,PICA_PROTO_INITRESPOK,PICA_PROTO_INITRESPOK_SIZE))
		{
		mp->tail[0]='O';
		mp->tail[1]='K';
		}
	
	c->state=PICA_CLSTATE_SENDINGRESP;
	printf("got PICA_PROTO_INITREQ from client\n");//debug
	}///////---------<<<<<<<<<<< new client
else
	{
	//// PICA_PROTO_VERDIFFER
	send(nc->sck,msg_VERDIFFER,msg_VERDIFFER_len,0);
	return 0;
	}

return 1;
}

unsigned int procmsg_CONNID(unsigned char* buf,unsigned int size,void* ptr)
{
struct PICA_proto_msg *mp;
struct newconn *nc=(struct newconn*)ptr;
unsigned int caller_id,callee_id;
struct cclink *link;

puts("received CONNID");//debug

caller_id=*((unsigned int*)(buf+2));
callee_id=*((unsigned int*)(buf+6));

printf("CONNID: caller_id=%u callee_id=%u\n",caller_id,callee_id);//debug

link=cclink_list_search(caller_id,callee_id);

if (!link)
	return 0;

puts("\ncclink found");//debug

printf("link->state = %i\n", link->state);//debug

if (link->state!=PICA_CCLINK_LOCAL_WAITCONNCLE && link->state!=PICA_CCLINK_LOCAL_WAITCONNCLR
	&& link->state!=PICA_CCLINK_N2NCLR_WAITCONNCLR  && link->state!=PICA_CCLINK_N2NCLE_WAITCONNCLE)
	return 0;

{
struct client *c;
//проверка IP адреса.
//IP адрес должен совпадать с адресом  клиента в управляющем соединении

if (link->state==PICA_CCLINK_LOCAL_WAITCONNCLE || link->state==PICA_CCLINK_N2NCLE_WAITCONNCLE)
	c = link->p2;
else if (link->state==PICA_CCLINK_LOCAL_WAITCONNCLR || link->state==PICA_CCLINK_N2NCLR_WAITCONNCLR)
	c = link->p1;

if (nc->addr.sin_addr.s_addr!=c->addr.sin_addr.s_addr)
	{
	puts("IP check failed");//debug
	return 0;
	}
}

if (link->state==PICA_CCLINK_LOCAL_WAITCONNCLE)
	{
	if(mp=client_wbuf_push(link->p1,PICA_PROTO_FOUND,PICA_PROTO_FOUND_SIZE))
		{
		*((unsigned int*)mp->tail)=callee_id;
		}
	else
		{
		puts("unable to send FOUND to caller");//debug
		cclink_list_delete(link);
		return 0;
		}
	}

if (link->state==PICA_CCLINK_N2NCLE_WAITCONNCLE)
	{
	if(mp=nodelink_wbuf_push(link->caller_node,PICA_PROTO_N2NALLOW,PICA_PROTO_N2NALLOW_SIZE))
		{
		*((unsigned int*)mp->tail)=caller_id;
		*((unsigned int*)(mp->tail+4))=callee_id;
		}
	else
		{
		puts("unable to send N2NALLOW to caller node");//debug
		cclink_list_delete(link);
		return 0;
		}
	}

cclink_activate(link,nc->sck);
newconn_free(nc);
return 1;
}

unsigned int procmsg_NODECONNREQ(unsigned char* buf,unsigned int size,void* ptr)
{
struct newconn *nc=(struct newconn*)ptr;
struct PICA_proto_msg *mp;

if (buf[2]==PICA_PROTO_VER_HIGH &&
	buf[3]==PICA_PROTO_VER_LOW)
	{
	////-прием входящего подключения
	//--------------------------
	struct nodelink *nl;
	nl=nodelink_list_addnew(nc);
	newconn_free(nc);
	if (!nl)
		return 0;

	if (mp=nodelink_wbuf_push(nl,PICA_PROTO_INITRESPOK,PICA_PROTO_INITRESPOK_SIZE))
		{
		mp->tail[0]='O';
		mp->tail[1]='K';
		}
	}
else
	{
	//// PICA_PROTO_VERDIFFER
	send(nc->sck,msg_VERDIFFER,msg_VERDIFFER_len,0);
	return 0;
	}

return 1;
}


void mapfunc_sendsearchreq(struct nodelink *p,unsigned int id)
{
struct PICA_proto_msg *mp;

mp=nodelink_wbuf_push(p,PICA_PROTO_SEARCH,PICA_PROTO_SEARCH_SIZE);

if (mp)
	*((unsigned int*)mp->tail) = id;
	
}

int nodelink_send_searchreq(unsigned int id)
{
if (!nodelink_list_count)
	return 0;

LISTMAP(nodelink,nodelink,mapfunc_sendsearchreq,id);
    
return 1;
}

unsigned int procmsg_CONNREQOUTG(unsigned char* buf,unsigned int size,void* ptr)
{
struct client *i,*o;//i - указатель на вызывающего клиента, o - вызываемого(если найден)
unsigned int callee_id;
struct PICA_proto_msg *mp;

puts("procmsg_CONNREQOUTGOING");//debug

i=(struct client *)ptr;

callee_id=*(unsigned int*)(buf+2);

if (o=client_tree_search(callee_id))
	{
	#warning "duplicated connections" // сделать проверку на наличие уже имеющегося соединения между клиентами
	// и если оно есть, то разрывать его, либо... ???? надо подумать

	#warning "self" // а еще - если клиент вызывает сам себя?

	//отправить o _CONNREQINC
	if (mp=client_wbuf_push(o,PICA_PROTO_CONNREQINC,PICA_PROTO_CONNREQINC_SIZE))
		{
		*((unsigned int*)mp->tail)=i->id;
		cclink_list_addlocal(i,o);
		return 1;
		}
	
	return 1;//сообщение отправить не удалось, но все равно возвращаем 1
	}
	
if (cclink_list_findwaitsearch(callee_id)/*search request for this id is already in progress*/ 
    		|| nodelink_send_searchreq(callee_id) /*make new search*/)
	{
	cclink_list_addn2nclr(i,callee_id);
    	return 1;
	}
	
//отправить i _NOTFOUND
if (mp=client_wbuf_push(i,PICA_PROTO_NOTFOUND,PICA_PROTO_NOTFOUND_SIZE))
	{
	*((unsigned int*)mp->tail)=callee_id;
	puts("sending NOTFOUND... put to senq q...");//debug
	}

return 1;
}

unsigned int procmsg_CONNALLOW(unsigned char* buf,unsigned int size,void* ptr)
{
struct client *caller,*callee;
struct cclink *link;
unsigned int caller_id;

puts("procmsg_CONNALLOW");//debug

callee=(struct client *)ptr;
caller_id=*(unsigned int*)(buf+2);

puts("procmsg_CONNALLOW_");//debug
printf("ptr=%X\n",ptr);//debug

puts("procmsg_CONNALLOW__");//debug


link=cclink_list_search(caller_id,callee->id);

if (!link)
	return 0;

if (link->state!=PICA_CCLINK_LOCAL_WAITREP &&
    link->state!=PICA_CCLINK_N2NCLE_WAITREP)
    return 0;

cclink_setwaitconn(link);
	
puts("procmsg_CONNALLOW - return 1");//debug
return 1;
}

unsigned int procmsg_CONNDENY(unsigned char* buf,unsigned int size,void* ptr)
{
struct client *caller,*callee;
struct cclink *link;
unsigned int caller_id;
struct PICA_proto_msg *mp;

puts("procmsg_procmsg_CONNDENY");//debug

callee=(struct client *)ptr;
caller_id=*(unsigned int*)(buf+2);

link=cclink_list_search(caller_id,callee->id);

if (!link)
	return 0;

caller = link -> p1;//check for NULL if not LOCAL

if (link->state!=PICA_CCLINK_LOCAL_WAITREP &&
    link->state!=PICA_CCLINK_N2NCLE_WAITREP)
	{
	cclink_list_delete(link);
	return 0;
	}

if (link->state==PICA_CCLINK_LOCAL_WAITREP)
	{
	//отправить caller _NOTFOUND
	if (mp=client_wbuf_push(caller,PICA_PROTO_NOTFOUND,PICA_PROTO_NOTFOUND_SIZE))
		{
		*((unsigned int*)mp->tail)=callee->id;
		}
	}
else if (link->state==PICA_CCLINK_N2NCLE_WAITREP)
	{
	//отправить caller N2NNOTFOUND
	if (mp=nodelink_wbuf_push(link->caller_node,PICA_PROTO_N2NNOTFOUND,PICA_PROTO_N2NNOTFOUND_SIZE))
		{
		*((unsigned int*)mp->tail)=caller_id;
		*( ((unsigned int*)mp->tail)+1)=callee->id;
		}
	}

cclink_list_delete(link);

return 1;
}

unsigned int procmsg_NODERESP(unsigned char* buf,unsigned int size,void* ptr)
{
switch(buf[0])
	{
	case PICA_PROTO_INITRESPOK:
	if (buf[2]!='O' || buf[3]!='K')
		return 0;

	*((int*)ptr)=0;
	break;
	case PICA_PROTO_VERDIFFER:
	((char*)ptr)[0]=buf[2];
	((char*)ptr)[1]=buf[3];
	break;
	}

return 1;
}

unsigned int procmsg_NEWNODE(unsigned char* buf,unsigned int size,void* ptr)
{
struct nodelink *n=(struct nodelink *)ptr;
struct PICA_nodeaddr na;

switch (buf[0])
	{
    	case PICA_PROTO_NEWNODE_IPV4:
	printf("NEWNODE_IPV4: ip %.16s port %hu\n",inet_ntoa(*(struct in_addr*)(buf+2)),ntohs(*(uint16_t*)(buf+6)));//debug
	{
	struct PICA_nodeaddr_ipv4 na_ipv4;
	
	na_ipv4.magick=PICA_PROTO_NEWNODE_IPV4;
	na_ipv4.addr=*(in_addr_t*)(buf+2);
	na_ipv4.port=*(in_port_t*)(buf+6);
	
	sprintf(na.addr,"%.16s",inet_ntoa(*(struct in_addr*)&na_ipv4.addr));
	na.port = na_ipv4.port;
	
	//int nodelink_attach_nodeaddr(struct nodelink *nl, unsigned int addr_type, void* nodeaddr, unsigned int nodeaddr_size)
	nodelink_attach_nodeaddr(n,na_ipv4.magick,&na_ipv4,sizeof(struct PICA_nodeaddr_ipv4));
	}
	break;
	case PICA_PROTO_NEWNODE_IPV6:
	#warning "TO DO"
	break;
	case PICA_PROTO_NEWNODE_DNS:
	#warning "TODO"
	break;
	}

PICA_nodeaddr_save(nodecfg.nodes_db_file, &na);//CONF filename

return 1;
}

unsigned int procmsg_NODELISTREQ(unsigned char* buf,unsigned int size,void* ptr)
{
struct PICA_proto_msg *mp;
struct nodelink *nlp;
unsigned int nl_size=0;
struct nodelink *n=0;
struct client *c=0;

switch(buf[0])
	{
	case PICA_PROTO_CLNODELISTREQ:
	c = (struct client *)ptr;
	break;
	case PICA_PROTO_NODELISTREQ:
	n = (struct nodelink *)ptr;
	break;
	}

unsigned char *nl_buf=malloc(65536);

if (!nl_buf)
    return 0;//ERR 

puts("NODELISTREQ");//debug

{//TEMP FIXME CONF
//собственный адрес узла
nl_buf[nl_size]=PICA_PROTO_NEWNODE_IPV4;
*((in_addr_t*)(nl_buf+nl_size+1))=inet_addr(my_addr);
*((uint16_t*)(nl_buf+nl_size+5))=(nodecfg.listen_port ? htons(atoi(nodecfg.listen_port)) :  htons(PICA_COMM_PORT));//CONF
nl_size+=PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;
}

nlp=nodelink_list_head;
while(nlp && nl_size < 65532)//MAP
	{
    	switch(nlp->addr_type)
		{
	    	case PICA_PROTO_NEWNODE_IPV4:
		if ( PICA_PROTO_NODELISTREQ == buf[0] && 
			 ((struct PICA_nodeaddr_ipv4*)nlp->node_addr)->addr==((struct PICA_nodeaddr_ipv4*)n->node_addr)->addr    &&
			((struct PICA_nodeaddr_ipv4*)nlp->node_addr)->port==((struct PICA_nodeaddr_ipv4*)n->node_addr)->port )
			break;//exclude requester's address
		 
		nl_buf[nl_size]=PICA_PROTO_NEWNODE_IPV4;
		*((in_addr_t*)(nl_buf+nl_size+1)) = ((struct PICA_nodeaddr_ipv4*)nlp->node_addr)->addr;
		*((uint16_t*)(nl_buf+nl_size+5)) = ((struct PICA_nodeaddr_ipv4*)nlp->node_addr)->port;
		nl_size += PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;//CONF 
		break;
		}
//#warning "set limit on list size, <65532 bytes!!!"    
	 nlp = nlp->next;
	}

switch(buf[0])
	{
	case PICA_PROTO_CLNODELISTREQ:
	mp =  client_wbuf_push( c, PICA_PROTO_CLNODELIST, nl_size+4);
	break;
	case PICA_PROTO_NODELISTREQ:
	mp = nodelink_wbuf_push( n, PICA_PROTO_NODELIST, nl_size+4);
	break;
	}

if (mp)
	{
	*((uint16_t*)mp->tail)=nl_size;
	memcpy(mp->tail+2,nl_buf,nl_size);
	}

free(nl_buf);
return 1;
}

unsigned int procmsg_NODELIST(unsigned char* buf,unsigned int size,void* ptr)
{
struct PICA_nodeaddr_ipv4 na_ipv4;

struct nodelink *n=(struct nodelink *)ptr;
unsigned int listsize=size-2-PICA_MSG_VARSIZE_INT16;
unsigned int listleft=listsize;

puts("NODELIST");//debug
printf("NODELIST_SIZE:%u\n",listsize);

while(listleft)
	{
#warning "strict error checking!!! -- listleft overflow, unknown list items, check listleft >= possible item size"
	if (listleft==listsize) //first entry, sender node's address
		{
		switch(buf[size-listleft])
			{
			case PICA_PROTO_NEWNODE_IPV4:
			na_ipv4.magick=PICA_PROTO_NEWNODE_IPV4;
			na_ipv4.addr=*(in_addr_t*)(buf+size-listleft+1);
			na_ipv4.port=*(in_port_t*)(buf+size-listleft+5);
			nodelink_attach_nodeaddr(n,na_ipv4.magick,&na_ipv4,sizeof(struct PICA_nodeaddr_ipv4));

			listleft-=PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;
			break;
			}
		continue;
		}
	else
		{
		struct PICA_nodeaddr na;
		//char addr[256];
		struct newconn nc;
		struct nodelink *nlp;

		memset(na.addr,0,256);
		memset(&nc,0,sizeof(struct newconn));

		switch(buf[size-listleft])
			{
			case PICA_PROTO_NEWNODE_IPV4:
			na_ipv4.magick=PICA_PROTO_NEWNODE_IPV4;
			na_ipv4.addr=*(in_addr_t*)(buf+size-listleft+1);
			na_ipv4.port=*(in_port_t*)(buf+size-listleft+5);

			sprintf(na.addr,"%.16s",inet_ntoa(*(struct in_addr*)&na_ipv4.addr));
			if (try_connect_to_node(na.addr,ntohs(na_ipv4.port),&nc))
				if (try_get_reply(&nc))
					{
					nlp=nodelink_list_addnew(&nc);
					send_newnode(nlp,my_addr);
					nodelink_attach_nodeaddr(nlp,na_ipv4.magick,&na_ipv4,sizeof(struct PICA_nodeaddr_ipv4));
					printf("LINKED NODE:%s\n",inet_ntoa(*(struct in_addr*)&na_ipv4.addr));//debug
					}
					
			na.port = ntohs(na_ipv4.port);

			listleft-=PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;
			break;
			}
		PICA_nodeaddr_save(nodecfg.nodes_db_file, &na);//CONF filename
		}
	}

return 1;
}

unsigned int procmsg_N2NFOUND(unsigned char* buf,unsigned int size,void* ptr)
{
struct cclink *cc;
struct nodelink *n=(struct nodelink *)ptr;
unsigned int callee_id=*(unsigned int*)(buf+2);
struct PICA_proto_msg *mp;

while(cc=cclink_list_findwaitsearch(callee_id))
	{
	cclink_attach_remotecle_node(cc,n);
	if(mp=nodelink_wbuf_push(n,PICA_PROTO_N2NCONNREQOUTG,PICA_PROTO_N2NCONNREQOUTG_SIZE))
		{
		*((unsigned int*)mp->tail) = cc->caller_id;
		*((unsigned int*)(mp->tail+4)) = callee_id;
		}	
	}
return 1;
}

unsigned int procmsg_SEARCH(unsigned char* buf,unsigned int size,void* ptr)
{
struct nodelink *n=(struct nodelink *)ptr;
unsigned int callee_id=*(unsigned int*)(buf+2);
struct PICA_proto_msg *mp;
struct client *callee;

if (callee=client_tree_search(callee_id))
	{
	if(mp=nodelink_wbuf_push(n,PICA_PROTO_N2NFOUND,PICA_PROTO_N2NFOUND_SIZE))
		{
		*((unsigned int*)mp->tail) = callee_id;
		}
	}
return 1;
}

unsigned int procmsg_N2NCONNREQOUTG(unsigned char* buf,unsigned int size,void* ptr)
{
struct nodelink *n=(struct nodelink *)ptr;
unsigned int caller_id,callee_id;
struct PICA_proto_msg *mp;
struct client *callee;

caller_id=*(unsigned int*)(buf+2);
callee_id=*(unsigned int*)(buf+6);

if (callee=client_tree_search(callee_id))
	{
	if (mp=client_wbuf_push(callee,PICA_PROTO_CONNREQINC,PICA_PROTO_CONNREQINC_SIZE))
		{
		*((unsigned int*)mp->tail)=caller_id;
		cclink_list_addn2ncle(caller_id, n, callee);
		}
	}
else
	{
	if(mp=nodelink_wbuf_push(n,PICA_PROTO_N2NNOTFOUND,PICA_PROTO_N2NNOTFOUND_SIZE))
		{
		*((unsigned int*)mp->tail) = caller_id;
		*((unsigned int*)(mp->tail+4)) = callee_id;
		}
	}
return 1;
}

unsigned int procmsg_N2NALLOW(unsigned char* buf,unsigned int size,void* ptr)
{
struct nodelink *n=(struct nodelink *)ptr;
unsigned int caller_id,callee_id;
struct PICA_proto_msg *mp;
struct cclink *cc;

caller_id=*(unsigned int*)(buf+2);
callee_id=*(unsigned int*)(buf+6);

cc=cclink_list_search(caller_id,callee_id);

if (cc)
	{
	if (mp=client_wbuf_push(cc->p1,PICA_PROTO_FOUND,PICA_PROTO_FOUND_SIZE))
		{
		*((unsigned int*)mp->tail)=callee_id;
	
		cclink_setwaitconn(cc);
		}
	}
return 1;
}

unsigned int procmsg_N2NNOTFOUND(unsigned char* buf,unsigned int size,void* ptr)
{
struct nodelink *n=(struct nodelink *)ptr;
unsigned int caller_id,callee_id;
struct PICA_proto_msg *mp;
struct cclink *cc;

caller_id=*(unsigned int*)(buf+2);
callee_id=*(unsigned int*)(buf+6);

cc=cclink_list_search(caller_id,callee_id);

if (cc)
	{
	if (mp=client_wbuf_push(cc->p1,PICA_PROTO_NOTFOUND,PICA_PROTO_NOTFOUND_SIZE))
		{
		*((unsigned int*)mp->tail)=callee_id;
		}
	cclink_list_delete(cc);
	}

return 1;
}

unsigned int procmsg_N2NMSG(unsigned char* buf,unsigned int size,void* ptr)
{
struct nodelink *n=(struct nodelink *)ptr;
struct PICA_proto_msg *mp;
unsigned int sender_id,receiver_id;
struct cclink *cc;
unsigned int len,datalen;

len=*(unsigned short*)(buf+2);
sender_id=*(unsigned int*)(buf+4);
receiver_id=*(unsigned int*)(buf+8);

if (len<8)
	return 0;
datalen=len-8;

cc=cclink_list_search(sender_id,receiver_id);

if (cc && cc->state==PICA_CCLINK_N2NCLE_ACTIVE)
	{
	if (datalen + cc->bufpos_p1p2 > cc->buflen_p1p2)
		{
		cclink_list_delete(cc);//CLOSING CCLINK DUE TO BUFER OVERRUN --------- FIXME FIX FIX FIX
		return 1;
		}

	memcpy(cc->buf_p1p2 + cc->bufpos_p1p2, buf+12,datalen);
	cc->bufpos_p1p2 += datalen;
	return 1;
	}
///////////////
cc=cclink_list_search(receiver_id,sender_id);

if (cc && cc->state==PICA_CCLINK_N2NCLR_ACTIVE)
	{
	if (datalen + cc->bufpos_p2p1 > cc->buflen_p2p1)
		{
		cclink_list_delete(cc);//CLOSING CCLINK DUE TO BUFER OVERRUN --------- FIXME FIX FIX FIX
		return 1;
		}

	memcpy(cc->buf_p2p1 + cc->bufpos_p2p1, buf+12,datalen);
	cc->bufpos_p2p1 += datalen;
	return 1;
	}

if(mp=nodelink_wbuf_push(n,PICA_PROTO_N2NNOTFOUND,PICA_PROTO_N2NNOTFOUND_SIZE))
	{
	*((unsigned int*)mp->tail) = sender_id;
	*((unsigned int*)(mp->tail+4)) = receiver_id;
	}

return 1;
}


struct cclink* cclink_list_findwaitsearch(unsigned int callee_id)
{
struct cclink *c;
c = cclink_list_head;
while(c)
	{
	if (c->callee_id == callee_id && c->state==PICA_CCLINK_N2NCLR_WAITSEARCH)
		return c;
	c=c->next;
	}
return 0;
}

struct cclink* cclink_list_search(unsigned int caller_id, unsigned int callee_id)
{
struct cclink *c;
c= cclink_list_head;

while(c)
	{
	if (c->caller_id == caller_id && c->callee_id == callee_id)
		return c;
	c=c->next;
	}
return 0;
}

void cclink_list_delete(struct cclink *l) 
{
//удаление из глобального списка 
if (l->prev)
	l->prev->next=l->next;
else
	cclink_list_head=l->next;

if (l->next)
	l->next->prev=l->prev;
else
	cclink_list_end=l->prev;

if (l->p1)
	if (l->sck_p1)
		{
		SHUTDOWN(l->sck_p1);
		CLOSE(l->sck_p1);
		}

if (l->p2)
	if (l->sck_p2)
		{
		SHUTDOWN(l->sck_p2);
		CLOSE(l->sck_p2);
		}


if (l->buf_p1p2)
	free(l->buf_p1p2);

if (l->buf_p2p1)
	free(l->buf_p2p1);

free(l);
cclink_list_count--;
}


//clr - caller
//cle - callee
// null value of clr or cle means that corresponding client is on remote node, is not local client
struct cclink* cclink_list_add(struct client *clr,struct client *cle)
{
struct cclink *l;

puts("cclink_list_add");//debug

l=(struct cclink*)calloc(sizeof(struct cclink),1);

if (!l)
	return 0;

//l->state=PICA_LINKSTATE_WAITREP;

l->p1=clr;
l->p2=cle;

//добавление в глобальный список
if (cclink_list_head)
	{
	cclink_list_end->next=l;
	l->prev=cclink_list_end;
	cclink_list_end=l;
	}
else
	{
	cclink_list_head=l;
	cclink_list_end=l;
	}

//timestamp
l->tmst=time(0);

cclink_list_count++;

return l;
}


void cclink_list_addlocal(struct client *clr,struct client *cle)
{
struct cclink *l;

l=cclink_list_add(clr,cle);

if (l)
	{
	l->state=PICA_CCLINK_LOCAL_WAITREP;
	l->caller_id = l->p1->id;
	l->callee_id = l->p2->id;
	}

}

void cclink_list_addn2nclr(struct client *clr,unsigned int callee_id)
{
struct cclink *l;

l=cclink_list_add(clr,0);

if (l)
	{
	l->state=PICA_CCLINK_N2NCLR_WAITSEARCH;
	l->caller_id = l->p1->id;
	l->callee_id = callee_id;
	}
}

void cclink_attach_remotecle_node(struct cclink *ccl, struct nodelink *callee_node)
{
if (ccl && ccl->state==PICA_CCLINK_N2NCLR_WAITSEARCH)
	{
	ccl->state=PICA_CCLINK_N2NCLR_WAITREP;
	ccl->callee_node=callee_node;
	}
}

void cclink_list_addn2ncle(unsigned int caller_id, struct nodelink *caller_node, struct client *cle)
{
struct cclink *l;

l=cclink_list_add(0,cle);

if (l)
	{
	l->state=PICA_CCLINK_N2NCLE_WAITREP;
	l->caller_id = caller_id;
	l->callee_id = l->p2->id;
	l->caller_node = caller_node;
	}

}

void cclink_setwaitconn(struct cclink *ccl)
{
switch (ccl->state)
	{
	case PICA_CCLINK_LOCAL_WAITREP:
	ccl->state=PICA_CCLINK_LOCAL_WAITCONNCLE;
	//
	break;
	case PICA_CCLINK_N2NCLR_WAITREP:
	ccl->state=PICA_CCLINK_N2NCLR_WAITCONNCLR;
	break;
	case PICA_CCLINK_N2NCLE_WAITREP:
	ccl->state=PICA_CCLINK_N2NCLE_WAITCONNCLE;
	break;
	default:
	    ;
	}
}

int cclink_allocbufs(struct cclink *ccl)
{
ccl->buf_p1p2 = malloc(DEFAULT_BUF_SIZE);
ccl->buf_p2p1 = malloc(DEFAULT_BUF_SIZE);
if (!ccl->buf_p1p2 || !ccl->buf_p2p1)
	{
	if (ccl->buf_p1p2)
		free(ccl->buf_p1p2);
	if (ccl->buf_p2p1)
		free(ccl->buf_p2p1);
	return 0;
	}
ccl->buflen_p1p2 = DEFAULT_BUF_SIZE;
ccl->buflen_p2p1 = DEFAULT_BUF_SIZE;
return 1;
}

void cclink_activate(struct cclink *ccl,SOCKET s)
{
switch(ccl->state)
	{
	case PICA_CCLINK_LOCAL_WAITCONNCLE:
	ccl->sck_p2 = s;
	ccl->state = PICA_CCLINK_LOCAL_WAITCONNCLR;
	break;
	case PICA_CCLINK_LOCAL_WAITCONNCLR:
	ccl->sck_p1 = s;
	if (!cclink_allocbufs(ccl))
		{
		cclink_list_delete(ccl);
		return;
		}
	ccl->state = PICA_CCLINK_LOCAL_ACTIVE;
	puts("caller cclink established");//debug
	break;
	case PICA_CCLINK_N2NCLR_WAITCONNCLR:
	ccl->sck_p1 = s;
	if (!cclink_allocbufs(ccl))
		{
		cclink_list_delete(ccl);
		return;
		}
	ccl->state = PICA_CCLINK_N2NCLR_ACTIVE;
	break;
	case PICA_CCLINK_N2NCLE_WAITCONNCLE:
	ccl->sck_p2 = s;
	if (!cclink_allocbufs(ccl))
		{
		cclink_list_delete(ccl);
		return;
		}
	ccl->state = PICA_CCLINK_N2NCLE_ACTIVE;
	break;
	}
}


int PICA_node_init()
{
struct sockaddr_in sd;

SSL_load_error_strings();
SSL_library_init(); 

puts("This product includes software developed by the OpenSSL Project\n\
for use in the OpenSSL Toolkit (http://www.openssl.org/\n");
puts("This product includes cryptographic software written by\n\
Eric Young (eay@cryptsoft.com)\n");
puts(SSLeay_version(SSLEAY_VERSION));


#ifdef WIN32
WSADATA wsd;
WSAStartup(MAKEWORD(2,2),&wsd);
#endif

//CONF -AF_INET6 ????
listen_comm_sck=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//ERR_CHECK

memset(&sd,0,sizeof(sd));

sd.sin_family=AF_INET;
sd.sin_addr.s_addr=INADDR_ANY;//CONF
sd.sin_port = (nodecfg.listen_port ? htons(atoi(nodecfg.listen_port)) :  htons(PICA_COMM_PORT));//CONF

bind(listen_comm_sck,(struct sockaddr*)&sd,sizeof(sd));
listen(listen_comm_sck,20);
//ERR_CHECK

{
int ret_comm;
unsigned long arg=1;
#ifdef WIN32
ret_comm=ioctlsocket(listen_comm_sck,FIONBIO,&arg);
// ret_data=ioctlsocket(listen_data_sck,FIONBIO,&arg);
// ret_data=ioctlsocket(listen_node_sck,FIONBIO,&arg);
#else
ret_comm=ioctl(listen_comm_sck,FIONBIO,(int*)&arg);
// ret_data=ioctl(listen_data_sck,FIONBIO,(int*)&arg);
// ret_data=ioctl(listen_node_sck,FIONBIO,(int*)&arg);
#endif
printf("ioctl ret_comm=%i\n",ret_comm);//debug
}

#ifdef NO_RAND_DEV  
PICA_rand_seed();
#endif

ctx=SSL_CTX_new(TLSv1_method());

if (!ctx)
;//ERR_CHECK

return 1;
}

//функция возвращает номер клиента id в бинарном виде, извлекая его из строки,
//которая возвращается функцией X509_NAME_oneline и представляет собой DN из сертификата клиента
int get_id_fromsubjstr(char* DN_str,unsigned int* id)
{
char* tmp1;
char* tmp2;

tmp1=strstr(DN_str,"/CN=");

if (!tmp1)
	return 0;

tmp2=strchr(tmp1,'#');

if (!tmp2)
	return 0;

*tmp2=0;

tmp1+=4;

if (tmp1==tmp2)
		return 0;

*id=(unsigned int)strtol(tmp1,0,10);

*tmp2='#';
return 1;
}


void newconn_close(struct newconn* nc)
{
CLOSE(nc->sck);


nc->sck=0;
nc->pos=0;   printf("newconn_close: closing connection\n");//debug
}

//функция ищет свободный элемент в массиве структур newconn и возвращает на него указатель
//В случае, если свободный элемент не найден, возвращается элемент с наиболее поздней отметкой времени,
//при этом соединение закрывается
struct newconn* newconn_add(struct newconn *ncs,int *pos)
{
time_t min;
int min_pos=0;
if (*pos<MAX_NEWCONNS && !ncs[*pos].sck)
	{
	goto ret;
	}
else
	{
	*pos=0;
	min=ncs->tmst;
	while(ncs[*pos].sck && *pos<MAX_NEWCONNS)
		{
		if (ncs[*pos].tmst<min)
			{
			min=ncs[*pos].tmst;
			min_pos=*pos;
			}
		(*pos)++;
		}

	if ( (*pos)==MAX_NEWCONNS)
		{
		*pos=min_pos;
		SHUTDOWN(ncs[min_pos].sck);
		CLOSE(ncs[min_pos].sck);
		}
	}

ret:
ncs[*pos].pos=0;
ncs[*pos].tmst=time(0);
return &ncs[(*pos)++];
}

void newconn_free(struct newconn* nc)
{
nc->sck=0;
//nc->pos=0; - pos value is being used in processmsgdatastream
}

int client_tree_add(struct client *ci)
{
struct client *i;
if (client_tree_root)
	{
	i=client_tree_root;
	
	do 
		{
		if (i->id==ci->id)
			return 0;

		if (ci->id < i->id)
			{
			if (i->left)
				i=i->left;
			else
				{
				i->left=ci;
				ci->up=i;
				return 1;
				}
			}
		else
			{
			if (i->right)
				i=i->right;
			else
				{
				i->right=ci;
				ci->up=i;
				return 1;
				}
			}
		}
	while(1);
	}
else
	client_tree_root=ci;

return 1;
}

struct client* client_tree_search(unsigned int id)//надо бы потестить
{
struct client* i_ptr;
i_ptr=client_tree_root;

printf("client_tree_search: searching for %u...\n",id);//debug

while(i_ptr)
	{
	if (i_ptr->id==id)
		return i_ptr;

	if (id < i_ptr->id)
		i_ptr=i_ptr->left;
	else
		i_ptr=i_ptr->right;
	}

puts("client_tree_search- id not found");//debug
return 0;
}

void client_tree_print(struct client *c)
{
if (!c)
	{
	puts("NULL");
	return;
	}

printf("%p: %u LEFT: %p, RIGHT: %p\n", c, c->id, c->left, c->right);

if (c->left)
	client_tree_print(c->left);

if (c->right)
	client_tree_print(c->right);
}

//удаление структуры из дерева 
void client_tree_remove(struct client* ci)
{
struct client** p_link;//указывает на left или right в родительском узле

if (!ci->up)
	{
	p_link = &client_tree_root;
	}
else
	{
	if (ci==ci->up->left)
		p_link=&(ci->up->left);
	else
		p_link=&(ci->up->right);
	}
	
	
if (!ci->left && !ci->right)
	{
	*p_link=0;
	return;
	}

if (ci->left && !ci->right)
	{
	ci->left->up=ci->up;
	*p_link=ci->left;
	return;
	}

if (!ci->left && ci->right)
	{
	ci->right->up=ci->up;
	*p_link=ci->right;
	return;
	}


	{
	struct client *lm;
	lm=ci->right;
		while(lm->left) lm=lm->left;//поиск самого левого узла правого поддерева

	if (lm!=ci->right)
		{  
		lm->up->left=lm->right;
		lm->right=ci->right;
		}
	lm->left=ci->left;	
	lm->up=ci->up;
	*p_link=lm;
	}
}

struct client *client_list_addnew(struct newconn *nc)
{
struct client* ci;

ci=(struct client *)calloc(1,sizeof(struct client));

if (!ci)	return 0;

ci->ssl_comm =SSL_new (ctx);

if (!ci->ssl_comm)
	{
	free(ci);
	return 0;
	}

if (client_list_end)
	{
	client_list_end->next=ci;
	ci->prev=client_list_end;
	client_list_end=ci;
	}
else
	{
	client_list_head=ci;
	client_list_end=ci;
	}

ci->sck_comm=nc->sck;
ci->addr=nc->addr;


SSL_set_fd(ci->ssl_comm,ci->sck_comm);

//ci->state=PICA_CLSTATE_SENDINGRESP;

printf("client_list_addnew: returning %X\n",ci);//debug
return ci;
}

void client_list_delete(struct client* ci)
{
printf("client_list_delete: ci=%X\n",ci);//debug

SSL_free(ci->ssl_comm);
//удаление из списка
if (ci->prev)
	ci->prev->next=ci->next;
else
	client_list_head=ci->next;

if (ci->next)
	ci->next->prev=ci->prev;
else
	client_list_end=ci->prev;

//удаление из дерева
if (client_tree_search(ci->id) == ci)
	{
	client_tree_remove(ci);
	client_tree_print(client_tree_root);//debug
	}


CLOSE(ci->sck_comm);

free(ci);
}

struct PICA_proto_msg* client_wbuf_push
	(struct client *c,unsigned int msgid,unsigned int size)
{
//Дальнейший вариант - размер буфера w_buf может увеличиться в
//этой функции путем вызова realloc, если размер сообщения превышает половину 
//текущего размера буфера
//Если буфер занят меньше, чем на половину, его размер может уменьшаться где-нибудь
//в другом месте, для экономии памяти 
	if (CL_WBUFSIZE - c->w_pos >= size) 
		{
		struct PICA_proto_msg *mp=(struct PICA_proto_msg *)(c->w_buf + c->w_pos);
		mp->head[0]=mp->head[1]=msgid;
		c->w_pos+=size;
		return mp;
		}
	else
		return 0;
}

struct nodelink *nodelink_list_addnew(struct newconn *nc)
{
struct nodelink *nl;

nl=(struct nodelink*)calloc(1,sizeof(struct nodelink));

if (!nl)
	return 0;

if (nodelink_list_end)
	{
	nodelink_list_end->next=nl;
	nl->prev=nodelink_list_end;
	nodelink_list_end=nl;
	}
else
	{
	nodelink_list_head=nl;
	nodelink_list_end=nl;
	}

nl->sck=nc->sck;
nl->addr=nc->addr;

nl->r_buf=calloc(1,DEFAULT_BUF_SIZE);
if (!nl->r_buf)
	{
	free(nl);
	return 0;
	}
nl->buflen_r=DEFAULT_BUF_SIZE;

printf("nodelink_list_addnew: returning %X\n",nl);//debug
nodelink_list_count++;
return nl;
}

void nodelink_list_delete(struct nodelink *n)
{
if (n->r_buf)
	free(n->r_buf);

if (n->w_buf)
	free(n->w_buf);

if (n->node_addr)
	free(n->node_addr);

CLOSE(n->sck);

if (n->prev)
	n->prev->next=n->next;
else
	nodelink_list_head=n->next;

if (n->next)
	n->next->prev=n->prev;
else
	nodelink_list_end=n->prev;

nodelink_list_count--;
free(n);
}

int nodelink_attach_nodeaddr(struct nodelink *nl, unsigned int addr_type, void* nodeaddr, unsigned int nodeaddr_size)
{
if (nl && nodeaddr)
	{
	if (nl->node_addr)
	    	free(nl->node_addr);
	    
	nl->node_addr=malloc(nodeaddr_size);
	if (!nl->node_addr)
		return 0;//ERR_CHECK
	memcpy(nl->node_addr,nodeaddr,nodeaddr_size);

	nl->addr_type=addr_type;
	return 1;
	}
return 0;
}

int nodelink_rbuf_grow(struct nodelink *nl)
{
unsigned char *p;

puts(__FUNCTION__);//debug

p=realloc(nl->r_buf,nl->buflen_r + DEFAULT_BUF_SIZE);

if (!p)
	{
	puts("out of memory");//debug
	return 0;
	}
nl->r_buf = p;
nl->buflen_r +=DEFAULT_BUF_SIZE;

return 1;
}

struct PICA_proto_msg* nodelink_wbuf_push
	(struct nodelink *nl,unsigned int msgid,unsigned int size)
{
struct PICA_proto_msg *mp;
    
if (!nl->w_buf)
	{
	nl->w_buf=calloc(1,DEFAULT_BUF_SIZE );
	if (!nl->w_buf)
		{
		puts("out of memory");//debug
		return 0;
		}
	nl->buflen_w=DEFAULT_BUF_SIZE;
	}

if ((nl->buflen_w - nl->w_pos) < size)
	{
	unsigned char *p;
	p=realloc(nl->w_buf,size + nl->w_pos);

	if (p) 
		{
		nl->w_buf=p;
		nl->buflen_w=size + nl->w_pos;
		}
	else 
		return 0;
	}
		
mp=(struct PICA_proto_msg *)(nl->w_buf + nl->w_pos);
mp->head[0]=mp->head[1]=msgid;
nl->w_pos+=size;
return mp;
}



// обработка различных таймаутов. Отправка пингов

void process_timeouts_newconn()
{
clock_t t;
int i;

t=time(0);

for (i=0;i<MAX_NEWCONNS;i++)
	{
	if (newconns[i].sck)
		{
		if (newconns[i].tmst<t)
			{
			if (t-newconns[i].tmst>NEWCONN_TIMEOUT)
				{
				newconn_close(newconns+i);
				puts("closing by timeout(1): ");//debug
				}
			}
		else if ( newconns[i].tmst-t>NEWCONN_TIMEOUT)
			{
			newconn_close(newconns+i);
			puts("closing by timeout(2): ");//debug
			}
		}
	}
}

void process_timeouts_c2c()
{
struct cclink *il;

il=cclink_list_head;

while(il)
	{
	switch(il->state)
		{
		case PICA_CCLINK_LOCAL_ACTIVE: 
		case PICA_CCLINK_N2NCLR_ACTIVE:
		case PICA_CCLINK_N2NCLE_ACTIVE:

		//idle timeout (>=60sec), update timestamp at process_c2c

		break;
		default:
		if ((time(0)- il->tmst)>TMO_CCLINK_WAITACTIVE)
			{
			struct cclink *dl;
			dl=il;
			il=il->next;
			cclink_list_delete(dl);
			puts("inactive cclink closed by timeout");//debug
			continue;
			}
		}
	il=il->next;
	}
}

int process_timeouts()
{
process_timeouts_newconn();
process_timeouts_c2c();
//..
return 1;
}

void set_select_fd(SOCKET s, fd_set *readfds, int *nfds)
{
FD_SET(s,readfds);

if (s > *nfds)
	*nfds=s;

//printf("set_select_fd([socket %i ])\n",s);//debug
}

void listen_set_fds(fd_set *readfds,int *nfds)
{
set_select_fd(listen_comm_sck,readfds,nfds);
}

void newconn_set_fds(fd_set *readfds,int *nfds)
{
int i;

for (i=0;i<MAX_NEWCONNS;i++)
	if (newconns[i].sck)
		set_select_fd(newconns[i].sck,readfds,nfds);
}

void c2n_set_fds(fd_set *readfds,int *nfds)
{
struct client *i_ptr; 

i_ptr=client_list_head;
while(i_ptr)
	{
	set_select_fd(i_ptr->sck_comm,readfds,nfds);

	i_ptr=i_ptr->next;
	}
}

void c2c_set_fds(fd_set *readfds,int *nfds)
{
struct cclink *cc;

cc=cclink_list_head;
while(cc)
	{
	if ( !cc->jam_p1p2 && (cc->state==PICA_CCLINK_LOCAL_ACTIVE || cc->state==PICA_CCLINK_N2NCLR_ACTIVE) )
		set_select_fd(cc->sck_p1,readfds,nfds);
	
	if ( !cc->jam_p2p1 && (cc->state==PICA_CCLINK_LOCAL_ACTIVE || cc->state==PICA_CCLINK_N2NCLE_ACTIVE) )
		set_select_fd(cc->sck_p2,readfds,nfds);

	cc=cc->next;
	}
}

void n2n_set_fds(fd_set *readfds,int *nfds)
{
struct nodelink *nl;
nl=nodelink_list_head;

while(nl)
	{
	set_select_fd(nl->sck,readfds,nfds);
	nl=nl->next;
	}
}

void process_listen_read(fd_set *readfds)
{
struct newconn *nc;
SOCKET s;
struct sockaddr_in addr;
int addrsize=sizeof(struct sockaddr_in);
if (FD_ISSET(listen_comm_sck,readfds))
	{
	puts("accept");//debug
	s=accept(listen_comm_sck,(struct sockaddr*)&addr,&addrsize);

	if (s>0)
		{
		nc=newconn_add(newconns,&newconns_pos);
		
		nc->sck=s;		
		nc->addr=addr;
		printf("accepted connection\n");//debug
		}
	else
		{
		newconn_free(nc);
		 
		perror("accept:");//debug
		printf("accept error!\n");//debug
		//ERR_CHECK
		}
	}

//IPv6
}

void process_newconn_read(fd_set *readfds)
{
int i,ret;

for (i=0;i<MAX_NEWCONNS;i++)
	if (newconns[i].sck && FD_ISSET(newconns[i].sck,readfds))
		{
		ret=recv(newconns[i].sck,newconns[i].buf+newconns[i].pos,NEWCONN_BUFSIZE - newconns[i].pos,0);

		if (ret<=0)
			{
			perror("process_newconn_read - recv:");//debug
			newconn_close(newconns+i);
			continue;
			}
		newconns[i].pos+=ret;
	
		if(!PICA_processdatastream(newconns[i].buf,&(newconns[i].pos),newconns+i  /*arg*/,_msginfo_newconn, MSGINFO_MSGSNUM(_msginfo_newconn) ))
			{
			puts("processdatastream error\n");//debug
			newconn_close(newconns+i);
			}
		//FD_CLR(newconns[i].sck,readfds);
		}
}



void process_c2n_read(fd_set *readfds)
{
struct client *i_ptr,*kill_ptr;
int ret;

i_ptr=client_list_head;
kill_ptr=0;

while (i_ptr)
	{
	if (FD_ISSET(i_ptr->sck_comm,readfds))
		switch(i_ptr->state)
		{
		case PICA_CLSTATE_CONNECTED:
		ret=SSL_read(i_ptr->ssl_comm,i_ptr->r_buf+i_ptr->r_pos,CL_RBUFSIZE-i_ptr->r_pos);
		
		if (!ret)
			kill_ptr=i_ptr;

		if (ret<0)
			switch(SSL_get_error(i_ptr->ssl_comm,ret))
				{
				case SSL_ERROR_WANT_WRITE:
				case SSL_ERROR_WANT_READ:
				break;
				default:
				kill_ptr=i_ptr;
				}
		
		if (ret>0)
			{
			i_ptr->r_pos+=ret;
			if(!PICA_processdatastream(i_ptr->r_buf,&(i_ptr->r_pos),i_ptr,_msginfo_comm, MSGINFO_MSGSNUM(_msginfo_comm) ))
						kill_ptr=i_ptr;

			}
		break;
		case PICA_CLSTATE_TLSNEGOTIATION:
		i_ptr->w_pos=1;//????
		//-------------- <<<<<<<<<<<<<<<<<<<<<<<<----------------------------------------
		break;
		};
	
	i_ptr=i_ptr->next;
	
	if (kill_ptr)
		{
		client_list_delete(kill_ptr);
		kill_ptr=0;
		}
	}

}

void process_c2c_read(fd_set *readfds)
{
int i,ret;
struct cclink *cc,*kill_ptr;

cc=cclink_list_head;
kill_ptr=0;

while(cc)
	{
	if ((cc->state==PICA_CCLINK_LOCAL_ACTIVE || cc->state==PICA_CCLINK_N2NCLR_ACTIVE) 
		&& FD_ISSET(cc->sck_p1,readfds) && !cc->jam_p1p2 )
		{
		ret=recv(cc->sck_p1,cc->buf_p1p2 + cc->bufpos_p1p2,cc->buflen_p1p2 - cc->bufpos_p1p2,0);
		printf("DATA recv  p1p2: ret=%i\n",ret);//debug
		if (ret>0)
			{
			cc->bufpos_p1p2+=ret;
			}
		else
			kill_ptr=cc;	
		}

	if ((cc->state==PICA_CCLINK_LOCAL_ACTIVE || cc->state==PICA_CCLINK_N2NCLE_ACTIVE) 
		&& FD_ISSET(cc->sck_p2,readfds)  && !cc->jam_p2p1 )
		{
		ret=recv(cc->sck_p2,cc->buf_p2p1 + cc->bufpos_p2p1,cc->buflen_p2p1 - cc->bufpos_p2p1,0);
		printf("DATA recv  p2p1: ret=%i\n",ret);//debug
		if (ret>0)
			{
			cc->bufpos_p2p1+=ret;
			}
		else
			kill_ptr=cc;	
		}


	cc=cc->next;
	
	if (kill_ptr)
		{
		cclink_list_delete(kill_ptr);
		kill_ptr=0;
		}
	}
}

void process_n2n_read(fd_set *readfds)
{
int i,ret;
struct nodelink *nl,*kill_ptr;

nl=nodelink_list_head;
kill_ptr=0;

while(nl)
	{
	if (FD_ISSET(nl->sck,readfds))
		{
		ret=recv(nl->sck,nl->r_buf+nl->r_pos,nl->buflen_r - nl->r_pos,0);
			
		if (ret<=0)
			{
			if (ret < 0)
				perror("n2n_read recv:");//debug
			kill_ptr=nl;
			}
		else
			{
			nl->r_pos+=ret;
		
			if(!PICA_processdatastream(nl->r_buf,&(nl->r_pos),nl,_msginfo_node, MSGINFO_MSGSNUM(_msginfo_node) ))
				kill_ptr=nl;

			if (nl->buflen_r == nl->r_pos)
				if (!nodelink_rbuf_grow(nl))
					kill_ptr=nl;
			}
		}
	    
	nl=nl->next;
	
	if (kill_ptr)
		{
		nodelink_list_delete(kill_ptr);puts("process_n2n_read - calling nodelink_list_delete");//debug
		kill_ptr=0;
		}
	}
}

void process_c2n_write()
{
struct client *i_ptr,*kill_ptr;
int ret;

i_ptr=client_list_head;
kill_ptr=0;

while(i_ptr)
	{
	//---------
	switch(i_ptr->state)
		{
		case PICA_CLSTATE_CONNECTED:
		if (!i_ptr->w_pos)			
		break;			

		if (!i_ptr->btw_ssl)
			i_ptr->btw_ssl=i_ptr->w_pos;
		
		ret=SSL_write(i_ptr->ssl_comm,i_ptr->w_buf,i_ptr->btw_ssl);
		
		printf("process_comm: write: ret of SSL_write=%i\n",ret);//debug
		
		if (ret==i_ptr->btw_ssl)
			{
			i_ptr->w_pos-=i_ptr->btw_ssl;
			i_ptr->btw_ssl=0;
			}

		if (!ret)
			kill_ptr=i_ptr;

		if (ret<0)
			{
			ret=SSL_get_error(i_ptr->ssl_comm,ret);
			if (ret!=SSL_ERROR_WANT_WRITE && ret!=SSL_ERROR_WANT_READ)
				kill_ptr=i_ptr;
			}
		break;
		case PICA_CLSTATE_SENDINGRESP:
		ret=send(i_ptr->sck_comm,i_ptr->w_buf,i_ptr->w_pos,0);
		printf("process_comm:  write: sendingresp w_pos=%u  ret=%i\n",i_ptr->w_pos,ret);//debug
		if (!ret)
			kill_ptr=i_ptr;
		
		if (ret==SOCKET_ERROR)
		;//ERR_CHECK
		
		if (ret < i_ptr->w_pos)
			memmove(i_ptr->w_buf,i_ptr->w_buf+ret,i_ptr->w_pos - ret); //ring buffer is better (??)

		i_ptr->w_pos-=ret;

		
		if (!i_ptr->w_pos)
			i_ptr->state=PICA_CLSTATE_TLSNEGOTIATION;
			
			puts("SENDINGRESP");//debug
		break;
		case PICA_CLSTATE_TLSNEGOTIATION:
		i_ptr->w_pos=0;
		ret=SSL_connect(i_ptr->ssl_comm);
		
		printf("wr SSL_connect=%i\n",ret);//debug
		
		if (!ret)
			kill_ptr=i_ptr;
		
		if (ret<0)
			{
			int eret;
			eret=SSL_get_error(i_ptr->ssl_comm,ret);
			switch(eret)
				{
				case SSL_ERROR_WANT_WRITE:
				i_ptr->w_pos=1;
				printf("wr WANT_WRITE\n");//debug
				break;
				case SSL_ERROR_WANT_READ:
	    printf("wr WANT_READ\n");//debug
				break;
				default:
	    printf("wr SSL_get_error=%i",eret);//debug
				kill_ptr=i_ptr;
				}
			}
		if (ret==1)
		//проверить сертификат пользователя
		{
		X509* client_cert;
		char* DN_str;

		printf("SSL connection using %s\n", SSL_get_cipher(i_ptr->ssl_comm));//debug

		client_cert=SSL_get_peer_certificate (i_ptr->ssl_comm);
		if (!client_cert)
			{
			//ERR_CHECK //нет сертификата
			kill_ptr=i_ptr;
			}
		//извлечение идентификационного  номера из сертификата
		DN_str=X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0);
		if (!DN_str)
			{
			//ERR_CHECK
			kill_ptr=i_ptr;
			}
		ret=get_id_fromsubjstr(DN_str,&i_ptr->id);
		if (!ret)
			{
			//ERR_CHECK //ошибка выделения id
			kill_ptr=i_ptr;
			}
    printf("user id=%u\n",i_ptr->id);//debug
		#warning "see comments below"
		//сделать проверку названия сети!!!!---------------------------<<<<<<<<<<<<<<<<<<<<<<
					
		OPENSSL_free(DN_str);
		X509_free(client_cert);
		//прицепить структуру к дереву
		if (client_tree_search(i_ptr->id))
		    ret = 0;//id already exists in tree
		else
			{
			ret=client_tree_add(i_ptr);
			client_tree_print(client_tree_root);//debug
			}
		if (!ret)
			{
			//ERR_CHECK  //не уникальный id
			kill_ptr=i_ptr;
			}
		i_ptr->state=PICA_CLSTATE_CONNECTED;
		}
		break;
		}
	//---------

	i_ptr=i_ptr->next;

	if (kill_ptr)
		{
		client_list_delete(kill_ptr);
		kill_ptr=0;
		}
	}
}

void process_c2c_write()
{
int i,ret;
struct cclink *cc,*kill_ptr;

cc=cclink_list_head;
kill_ptr=0;

while(cc)
	{
	if (cc->bufpos_p1p2/* && (cc->state==PICA_CCLINK_LOCAL_ACTIVE || cc->state==PICA_CCLINK_N2NCLE_ACTIVE)*/)
		{
		if (cc->state==PICA_CCLINK_N2NCLR_ACTIVE)//receiver is on remote node
			{
			int sendlen;
			struct PICA_proto_msg *mp;
			
			sendlen = (cc->bufpos_p1p2 > PICA_PROTO_N2NMSG_MAXDATASIZE) ? PICA_PROTO_N2NMSG_MAXDATASIZE : cc->bufpos_p1p2;

			if(mp=nodelink_wbuf_push(cc->callee_node,PICA_PROTO_N2NMSG,sendlen+12))
				{
				*((unsigned short*)mp->tail) = 8+sendlen;
				*((unsigned int*)(mp->tail+2))=cc->caller_id;
				*((unsigned int*)(mp->tail+6))=cc->callee_id;
				memcpy(mp->tail+10, cc->buf_p1p2, sendlen);
				ret=sendlen;
				}
			else
				ret=0;
			}
		else
			ret=send(cc->sck_p2,cc->buf_p1p2,cc->bufpos_p1p2,MSG_NOSIGNAL);

		printf("DATA send  p1p2: ret=%i\n",ret);//debug
		if (ret>0)
			{
			if (ret < cc->bufpos_p1p2)
				memmove(cc->buf_p1p2,cc->buf_p1p2+ret,cc->bufpos_p1p2-ret);//may be it's better to implement ring buffer here
			cc->bufpos_p1p2-=ret;
			cc->jam_p1p2=0;
			}

		if (ret==0)
			{
			kill_ptr=cc;
			}
		if (ret==-1)
			{
			#ifdef WIN32
			ret=WSAGetLastError();
			if (ret==WSAEWOULDBLOCK || ret==WSAENOBUFS)
				cc->jam_p1p2=1;
			else
				{
				kill_ptr=cc;
				}
			#else
			ret=errno;
			if (ret==EAGAIN || ret==ENOBUFS)
				cc->jam_p1p2=1;
			else
				{
				kill_ptr=cc;
				}
			#endif
			}
		
		}
	if (cc->bufpos_p2p1 /*&& (cc->state==PICA_CCLINK_LOCAL_ACTIVE || cc->state==PICA_CCLINK_N2NCLR_ACTIVE)*/)
		{
		if (cc->state==PICA_CCLINK_N2NCLE_ACTIVE)//receiver is on remote node
			{
			int sendlen;
			struct PICA_proto_msg *mp;
			
			sendlen = (cc->bufpos_p2p1 > PICA_PROTO_N2NMSG_MAXDATASIZE) ? PICA_PROTO_N2NMSG_MAXDATASIZE : cc->bufpos_p2p1;

			if(mp=nodelink_wbuf_push(cc->caller_node,PICA_PROTO_N2NMSG,sendlen+12))
				{
				*((unsigned short*)mp->tail) = 8+sendlen;
				*((unsigned int*)(mp->tail+2))=cc->callee_id;
				*((unsigned int*)(mp->tail+6))=cc->caller_id;
				memcpy(mp->tail+10, cc->buf_p2p1, sendlen);
				ret=sendlen;
				}
			else
				ret=0;
			}
		else
			ret=send(cc->sck_p1,cc->buf_p2p1,cc->bufpos_p2p1,MSG_NOSIGNAL);

		printf("DATA send  p2p1: ret=%i\n",ret);//debug
		if (ret>0)
			{
			if (ret < cc->bufpos_p2p1)
				memmove(cc->buf_p2p1,cc->buf_p2p1+ret,cc->bufpos_p2p1-ret);//may be it's better to implement ring buffer here
			cc->bufpos_p2p1-=ret;
			cc->jam_p2p1=0;
			}

		if (ret==0)
			{
			kill_ptr=cc;
			}
		if (ret==-1)
			{
			#ifdef WIN32
			ret=WSAGetLastError();
			if (ret==WSAEWOULDBLOCK || ret==WSAENOBUFS)
				cc->jam_p2p1=1;
			else
				{
				kill_ptr=cc;
				}
			#else
			ret=errno;
			if (ret==EAGAIN || ret==ENOBUFS)
				cc->jam_p2p1=1;
			else
				{
				kill_ptr=cc;
				}
			#endif
			
			}
		
		}
		
	cc=cc->next;
	
	if (kill_ptr)
		{
		cclink_list_delete(kill_ptr);
		kill_ptr=0;
		}
	}
}

void process_n2n_write()
{
int ret;
struct nodelink *nl,*kill_ptr;

nl=nodelink_list_head;
kill_ptr=0;

while(nl)
	{
	if (nl->w_pos>0)
		{
		ret=send(nl->sck,nl->w_buf,nl->w_pos,MSG_NOSIGNAL);

		if (ret>0)
			{
			if (ret < nl->w_pos)
				memmove(nl->w_buf,nl->w_buf+ret,nl->w_pos-ret);//may be it's better to implement ring buffer here
			nl->w_pos-=ret;
			}
		if (ret<0)
			{
			#ifdef WIN32
			ret=WSAGetLastError();
			if (!(ret==WSAEWOULDBLOCK || ret==WSAENOBUFS))
				kill_ptr=nl;
			#else
			ret=errno;
			if (!(ret==EAGAIN || ret==ENOBUFS || ret == EINTR))
				kill_ptr=nl;
			#endif
			}
		if (ret==0)
			kill_ptr=nl;
		}

	nl=nl->next;
	
	if (kill_ptr)
		{
		nodelink_list_delete(kill_ptr);puts("process_n2n_write - calling nodelink_list_delete");//debug
		kill_ptr=0;
		}
	}
}

int node_loop()
{
fd_set fds;
struct timeval tv; 
int nfds,ret;
    
do
	{
	FD_ZERO(&fds);
	tv.tv_sec=SELECT_TIMEOUT;
	tv.tv_usec=0;

	listen_set_fds(&fds,&nfds);
	newconn_set_fds(&fds,&nfds);
	c2n_set_fds(&fds,&nfds);
	c2c_set_fds(&fds,&nfds);
	n2n_set_fds(&fds,&nfds);
	
	ret=select(nfds+1,&fds,0,0,&tv);
	
	if (ret<0)
		{
		perror("node_loop-select error ");
		//ERR_CHECK
		return -1;
		}

	if (ret>0)
		{
		process_c2n_read(&fds);
		process_c2c_read(&fds);
		process_n2n_read(&fds);
		process_newconn_read(&fds);
		process_listen_read(&fds);
		}
		
		
	process_c2n_write();
	process_c2c_write();
	process_n2n_write();
	
	process_timeouts();
	}
while(1);////<<<<<<<<<<
return 0;
}

int main(int argc,char** argv)
{
printf("PicaPica node started\n");//debug

PICA_nodeconfig_load(argv[1]);

if (!PICA_node_init())
	return -1;

//if (PICA_node_joinskynet("nodelist")<=0)//CONF имя файла
	/*return -1*/;//вывести предупреждение, что ни к одному другому узлу подключиться не удалось

PICA_node_joinskynet(nodecfg.nodes_db_file, nodecfg.announced_addr);//CONF-CONF имя файла с адресами узлов, свой адрес

printf("nodecfg.announced_addr =%s\n",nodecfg.announced_addr);//debug
printf("nodecfg.listen_port =%s\n",nodecfg.listen_port);//debug
printf("nodecfg.nodes_db_file =%s\n",nodecfg.nodes_db_file);//debug

my_addr = nodecfg.announced_addr;//TEMP FIXME 

return node_loop();
}