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

#include "icqoscar.h"

// SERVER-LIST UPDATE BOARD
//

void CIcqProto::servlistBeginOperation(int operationCount, int bImport)
{
	if (operationCount)
	{ // check if we should send operation begin packet
		if (!servlistEditCount)
			icq_sendServerBeginOperation(bImport);
		// update count of active operations
		servlistEditCount += operationCount;
#ifdef _DEBUG
		debugLogA("Server-List: Begin operation processed (%d operations active)", servlistEditCount);
#endif
	}
}

void CIcqProto::servlistEndOperation(int operationCount)
{
	if (operationCount)
	{
		if (operationCount > servlistEditCount)
		{ // sanity check
			debugLogA("Error: Server-List End operation is not paired!");
			operationCount = servlistEditCount;
		}
		// update count of active operations
		servlistEditCount -= operationCount;
		// check if we should send operation end packet
		if (!servlistEditCount)
			icq_sendServerEndOperation();
#ifdef _DEBUG
		debugLogA("Server-List: End operation processed (%d operations active)", servlistEditCount);
#endif
	}
}

void __cdecl CIcqProto::servlistQueueThread(void *param)
{
	int* queueState = ( int* )param;

#ifdef _DEBUG
	debugLogA("Server-List: Starting Update board.");
#endif

	SleepEx(50, FALSE);
	// handle server-list requests queue
	servlistQueueMutex->Enter();
	while (servlistQueueCount)
	{
		ssiqueueditems* pItem = NULL;
		int bItemDouble;
		WORD wItemAction;
		icq_packet groupPacket = {0};
		icq_packet groupPacket2 = {0}; 
		cookie_servlist_action* pGroupCookie = NULL;
		int nEndOperations;

		// first check if the state is calm
		while (*queueState) 
		{
			int i;
			time_t tNow = time(NULL);
			int bFound = FALSE;

			for (i = 0; i < servlistQueueCount; i++)
			{ // check if we do not have some expired items to handle, otherwise keep sleeping
				if ((servlistQueueList[i]->tAdded + servlistQueueList[i]->dwTimeout) < tNow)
				{ // got expired item, stop sleep even when changes goes on
					bFound = TRUE;
					break;
				}
			}
			if (bFound) break;
			// reset queue state, keep sleeping
			*queueState = FALSE; 
			servlistQueueMutex->Leave();
			SleepEx(100, TRUE);
			servlistQueueMutex->Enter();
		}
		if (!icqOnline())
		{ // do not try to send packets if offline
			servlistQueueMutex->Leave();
			SleepEx(100, TRUE);
			servlistQueueMutex->Enter();
			continue;
		}
#ifdef _DEBUG
		debugLogA("Server-List: %d items in queue.", servlistQueueCount);
#endif
		// take the oldest item (keep the board FIFO)
		pItem = servlistQueueList[0]; // take first (queue contains at least one item here)
		wItemAction = (WORD)(pItem->pItems[0]->dwOperation & SSOF_ACTIONMASK);
		bItemDouble = pItem->pItems[0]->dwOperation & SSOG_DOUBLE;
		// check item rate - too high -> sleep
		m_ratesMutex->Enter();
		{
			WORD wRateGroup = m_rates->getGroupFromSNAC(ICQ_LISTS_FAMILY, wItemAction);
			int nRateLevel = bItemDouble ? RML_IDLE_30 : RML_IDLE_10;

			while (m_rates->getNextRateLevel(wRateGroup) < m_rates->getLimitLevel(wRateGroup, nRateLevel))
			{ // the rate is higher, keep sleeping
				int nDelay = m_rates->getDelayToLimitLevel(wRateGroup, nRateLevel);

				m_ratesMutex->Leave();
				// do not keep the queue frozen
				servlistQueueMutex->Leave();
				if (nDelay < 10) nDelay = 10;
#ifdef _DEBUG
				debugLogA("Server-List: Delaying %dms [Rates]", nDelay);
#endif
				SleepEx(nDelay, FALSE);
				// check if the rate is now ok
				servlistQueueMutex->Enter();
				m_ratesMutex->Enter();
			}    
		}
		m_ratesMutex->Leave();
		{ // setup group packet(s) & cookie
			int totalSize = 0;
			int i;
			cookie_servlist_action *pGroupCookie;
			DWORD dwGroupCookie;
			// determine the total size of the packet
			for(i = 0; i < pItem->nItems; i++)
				totalSize += pItem->pItems[i]->packet.wLen - 0x10;

			// process begin & end operation flags
			{
				int bImportOperation = FALSE;
				int nBeginOperations = 0;

				nEndOperations = 0;
				for(i = 0; i < pItem->nItems; i++)
				{ // collect begin & end operation flags
					if (pItem->pItems[i]->dwOperation & SSOF_BEGIN_OPERATION)
						nBeginOperations++;
					if (pItem->pItems[i]->dwOperation & SSOF_END_OPERATION)
						nEndOperations++;
					// check if the operation is import
					if (pItem->pItems[i]->dwOperation & SSOF_IMPORT_OPERATION)
						bImportOperation = TRUE;
				}
				// really begin operation if requested
				if (nBeginOperations)
					servlistBeginOperation(nBeginOperations, bImportOperation);
			}

			if (pItem->nItems > 1)
			{ // pack all packet's data, create group cookie
				pGroupCookie = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action));
				pGroupCookie->dwAction = SSA_ACTION_GROUP;
				pGroupCookie->dwGroupCount = pItem->nItems;
				pGroupCookie->pGroupItems = (cookie_servlist_action**)SAFE_MALLOC(pItem->nItems * sizeof(cookie_servlist_action*));
				for (i = 0; i < pItem->nItems; i++)
				{ // build group cookie data - assign cookies datas
					pGroupCookie->pGroupItems[i] = pItem->pItems[i]->cookie;
					// release the separate cookie id
					FreeCookieByData(CKT_SERVERLIST, pItem->pItems[i]->cookie);
				}
				// allocate cookie id
				dwGroupCookie = AllocateCookie(CKT_SERVERLIST, wItemAction, 0, pGroupCookie);
				// prepare packet data
				serverPacketInit(&groupPacket, (WORD)(totalSize + 0x0A)); // FLAP size added inside
				packFNACHeader(&groupPacket, ICQ_LISTS_FAMILY, wItemAction, 0, dwGroupCookie);
				for (i = 0; i < pItem->nItems; i++)
					packBuffer(&groupPacket, pItem->pItems[i]->packet.pData + 0x10, (WORD)(pItem->pItems[i]->packet.wLen - 0x10));

				if (bItemDouble)
				{ // prepare second packet
					wItemAction = ((servlistgroupitemdouble*)(pItem->pItems[0]))->wAction2;
					totalSize = 0;
					// determine the total size of the packet
					for(i = 0; i < pItem->nItems; i++)
						totalSize += ((servlistgroupitemdouble*)(pItem->pItems[i]))->packet2.wLen - 0x10;

					pGroupCookie = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action));
					pGroupCookie->dwAction = SSA_ACTION_GROUP;
					pGroupCookie->dwGroupCount = pItem->nItems;
					pGroupCookie->pGroupItems = (cookie_servlist_action**)SAFE_MALLOC(pItem->nItems * sizeof(cookie_servlist_action*));
					for (i = 0; i < pItem->nItems; i++)
						pGroupCookie->pGroupItems[i] = pItem->pItems[i]->cookie;
					// allocate cookie id
					dwGroupCookie = AllocateCookie(CKT_SERVERLIST, wItemAction, 0, pGroupCookie);
					// prepare packet data
					serverPacketInit(&groupPacket2, (WORD)(totalSize + 0x0A)); // FLAP size added inside
					packFNACHeader(&groupPacket2, ICQ_LISTS_FAMILY, wItemAction, 0, dwGroupCookie);
					for (i = 0; i < pItem->nItems; i++)
						packBuffer(&groupPacket2, ((servlistgroupitemdouble*)(pItem->pItems[i]))->packet2.pData + 0x10, (WORD)(((servlistgroupitemdouble*)(pItem->pItems[i]))->packet2.wLen - 0x10));
				}
			}
			else
			{ // just send the one packet, do not create action group
				pGroupCookie = pItem->pItems[0]->cookie;
				memcpy(&groupPacket, &pItem->pItems[0]->packet, sizeof(icq_packet));
				if (bItemDouble)
					memcpy(&groupPacket2, &((servlistgroupitemdouble*)(pItem->pItems[0]))->packet2, sizeof(icq_packet));
			}

			{ // remove grouped item from queue & release grouped item
				servlistQueueCount--;
				servlistQueueList[0] = servlistQueueList[servlistQueueCount];

				for (i = 0; i < pItem->nItems; i++)
				{ // release memory
					if (pItem->nItems > 1)
					{ // free the packet only if we created the group packet
						SAFE_FREE((void**)&pItem->pItems[i]->packet.pData);
						if (pItem->pItems[i]->dwOperation & SSOG_DOUBLE)
							SAFE_FREE((void**)&((servlistgroupitemdouble*)(pItem->pItems[i]))->packet2.pData);
					}
					SAFE_FREE((void**)&pItem->pItems[i]);
					break;
				}
				SAFE_FREE((void**)&pItem);
				// resize the queue
				if (servlistQueueSize > servlistQueueCount + 6)
				{
					servlistQueueSize -= 4;
					servlistQueueList = (ssiqueueditems**)SAFE_REALLOC(servlistQueueList, servlistQueueSize * sizeof(ssiqueueditems*));
				}
			}
		}
		servlistQueueMutex->Leave();
		// send group packet
		sendServPacket(&groupPacket);
		// send second group packet (if present)
		if (bItemDouble)
			sendServPacket(&groupPacket2);
		// process end operation marks
		if (nEndOperations)
			servlistEndOperation(nEndOperations);
		// loose the loop a bit
		SleepEx(100, TRUE);
		servlistQueueMutex->Enter();
	}
	// clean-up thread
	CloseHandle(servlistQueueThreadHandle);
	servlistQueueThreadHandle = NULL;
	servlistQueueMutex->Leave();
#ifdef _DEBUG
	debugLogA("Server-List: Update Board ending.");
#endif
}

void CIcqProto::servlistQueueAddGroupItem(servlistgroupitem* pGroupItem, int dwTimeout)
{
	icq_lock l(servlistQueueMutex);

	{ // add the packet to queue
		DWORD dwMark = pGroupItem->dwOperation & SSOF_GROUPINGMASK;
		ssiqueueditems* pItem = NULL;

		// try to find compatible item
		for (int i = 0; i < servlistQueueCount; i++)
		{
			if ((servlistQueueList[i]->pItems[0]->dwOperation & SSOF_GROUPINGMASK) == dwMark && servlistQueueList[i]->nItems < MAX_SERVLIST_PACKET_ITEMS)
			{ // found compatible item, check if it does not contain operation for the same server-list item
				pItem = servlistQueueList[i];

				for (int j = 0; j < pItem->nItems; j++)
					if (pItem->pItems[j]->cookie->wContactId == pGroupItem->cookie->wContactId &&
						pItem->pItems[j]->cookie->wGroupId == pGroupItem->cookie->wGroupId)
					{
						pItem = NULL;
						break;
					}
					// cannot send two operations for the same server-list record in one packet, look for another
					if (!pItem) continue;

#ifdef _DEBUG
					debugLogA("Server-List: Adding packet to item #%d with operation %x.", i, servlistQueueList[i]->pItems[0]->dwOperation);
#endif
					break;
			}
		}
		if (!pItem)
		{ // compatible item was not found, create new one, add to queue
			pItem = (ssiqueueditems*)SAFE_MALLOC(sizeof(ssiqueueditems));
			pItem->tAdded = time(NULL);
			pItem->dwTimeout = dwTimeout;

			if (servlistQueueCount == servlistQueueSize)
			{ // resize the queue - it is too small
				servlistQueueSize += 4;
				servlistQueueList = (ssiqueueditems**)SAFE_REALLOC(servlistQueueList, servlistQueueSize * sizeof(ssiqueueditems*));     
			}
			// really add to queue
			servlistQueueList[servlistQueueCount++] = pItem;
#ifdef _DEBUG
			debugLogA("Server-List: Adding new item to queue.");
#endif
		} 
		else if (pItem->dwTimeout > dwTimeout)
		{ // if the timeout of currently added packet is shorter, update the previous one
			pItem->dwTimeout = dwTimeout;
		}
		// add GroupItem to queueditems (pItem)
		pItem->pItems[pItem->nItems++] = pGroupItem;
	}
	// wake up board thread (keep sleeping or start new one)  
	if (!servlistQueueThreadHandle)
	{
		// create new board thread
		servlistQueueThreadHandle = ForkThreadEx(&CIcqProto::servlistQueueThread, &servlistQueueState, 0);
	}
	else // signal thread, that queue was changed during sleep
		servlistQueueState = TRUE;
}

int CIcqProto::servlistHandlePrimitives(DWORD dwOperation)
{
	if (dwOperation & SSO_BEGIN_OPERATION)
	{ // operation starting, no action ready yet
		servlistBeginOperation(1, dwOperation & SSOF_IMPORT_OPERATION);
		return TRUE;
	}
	else if (dwOperation & SSO_END_OPERATION)
	{ // operation ending without action
		servlistEndOperation(1);
		return TRUE;
	}

	return FALSE;
}

void CIcqProto::servlistPostPacket(icq_packet* packet, DWORD dwCookie, DWORD dwOperation, DWORD dwTimeout)
{
	cookie_servlist_action* pCookie;

	if (servlistHandlePrimitives(dwOperation))
		return;

	if (!FindCookie(dwCookie, NULL, (void**)&pCookie))
		return; // invalid cookie

	if (dwOperation & SSOF_SEND_DIRECTLY)
	{ // send directly - this is for some special cases
		// begin operation if requested
		if (dwOperation & SSOF_BEGIN_OPERATION)
			servlistBeginOperation(1, dwOperation & SSOF_IMPORT_OPERATION);

		// send the packet
		sendServPacket(packet);

		// end operation if requested
		if (dwOperation & SSOF_END_OPERATION)
			servlistEndOperation(1);
	}
	else
	{ // add to server-list update board
		servlistgroupitem* pGroupItem;

		// prepare group item
		pGroupItem = (servlistgroupitem*)SAFE_MALLOC(sizeof(servlistgroupitem));
		pGroupItem->dwOperation = dwOperation;
		pGroupItem->cookie = pCookie;
		// packet data are alloced, keep them until they are sent
		memcpy(&pGroupItem->packet, packet, sizeof(icq_packet));

		servlistQueueAddGroupItem(pGroupItem, dwTimeout);
	}
}

void CIcqProto::servlistPostPacketDouble(icq_packet* packet1, DWORD dwCookie, DWORD dwOperation, DWORD dwTimeout, icq_packet* packet2, WORD wAction2)
{
	cookie_servlist_action* pCookie;

	if (servlistHandlePrimitives(dwOperation))
		return;

	if (!FindCookie(dwCookie, NULL, (void**)&pCookie))
		return; // invalid cookie

	if (dwOperation & SSOF_SEND_DIRECTLY)
	{ // send directly - this is for some special cases
		// begin operation if requested
		if (dwOperation & SSOF_BEGIN_OPERATION)
			servlistBeginOperation(1, dwOperation & SSOF_IMPORT_OPERATION);

		// send the packets
		sendServPacket(packet1);
		sendServPacket(packet2);

		// end operation if requested
		if (dwOperation & SSOF_END_OPERATION)
			servlistEndOperation(1);
	}
	else
	{ // add to server-list update board
		servlistgroupitemdouble* pGroupItem;

		// prepare group item
		pGroupItem = (servlistgroupitemdouble*)SAFE_MALLOC(sizeof(servlistgroupitemdouble));
		pGroupItem->dwOperation = dwOperation;
		pGroupItem->cookie = pCookie;
		pGroupItem->wAction2 = wAction2;
		// packets data are alloced, keep them until they are sent
		memcpy(&pGroupItem->packet, packet1, sizeof(icq_packet));
		memcpy(&pGroupItem->packet2, packet2, sizeof(icq_packet));

		servlistQueueAddGroupItem((servlistgroupitem*)pGroupItem, dwTimeout);
	}
}

void CIcqProto::servlistProcessLogin()
{
	// reset edit state counter
	servlistEditCount = 0;

	/// TODO: preserve queue state in DB! restore here!

	// if the server-list queue contains items and thread is not running, start it
	if (servlistQueueCount && !servlistQueueThreadHandle)
		servlistQueueThreadHandle = ForkThreadEx(&CIcqProto::servlistQueueThread, &servlistQueueState, 0);
}

// HERE ENDS SERVER-LIST UPDATE BOARD IMPLEMENTATION //
///////////////////////////////////////////////////////
//===================================================//

// PENDING SERVER-LIST OPERATIONS
//
#define ITEM_PENDING_CONTACT    0x01
#define ITEM_PENDING_GROUP      0x02

#define CALLBACK_RESULT_CONTINUE  0x00
#define CALLBACK_RESULT_POSTPONE  0x0D
#define CALLBACK_RESULT_PURGE     0x10


#define SPOF_AUTO_CREATE_ITEM     0x01

int CIcqProto::servlistPendingFindItem(int nType, MCONTACT hContact, const char *pszGroup)
{
	if (servlistPendingList)
		for (int i = 0; i < servlistPendingCount; i++)
			if (servlistPendingList[i]->nType == nType)
			{ 
				if (((nType == ITEM_PENDING_CONTACT) && (servlistPendingList[i]->hContact == hContact)) ||
					((nType == ITEM_PENDING_GROUP) && (!strcmpnull(servlistPendingList[i]->szGroup, pszGroup))))
					return i;
			}
			return -1;
}


void CIcqProto::servlistPendingAddItem(servlistpendingitem *pItem)
{
	if (servlistPendingCount >= servlistPendingSize) // add new
	{
		servlistPendingSize += 10;
		servlistPendingList = (servlistpendingitem**)SAFE_REALLOC(servlistPendingList, servlistPendingSize * sizeof(servlistpendingitem*));
	}

	servlistPendingList[servlistPendingCount++] = pItem;
}


servlistpendingitem* CIcqProto::servlistPendingRemoveItem(int nType, MCONTACT hContact, const char *pszGroup)
{ // unregister pending item, trigger pending operations
	int iItem;
	servlistpendingitem *pItem = NULL;

	icq_lock l(servlistMutex);

	if ((iItem = servlistPendingFindItem(nType, hContact, pszGroup)) != -1)
	{ // found, remove from the pending list
		pItem = servlistPendingList[iItem];

		servlistPendingList[iItem] = servlistPendingList[--servlistPendingCount];

		if (servlistPendingCount + 10 < servlistPendingSize)
		{
			servlistPendingSize -= 5;
			servlistPendingList = (servlistpendingitem**)SAFE_REALLOC(servlistPendingList, servlistPendingSize * sizeof(servlistpendingitem*));
		}
		// was the first operation was created automatically to postpone ItemAdd?
		if (pItem->operations && pItem->operations[0].flags & SPOF_AUTO_CREATE_ITEM)
		{ // yes, add new item
			servlistpendingitem *pNewItem = (servlistpendingitem*)SAFE_MALLOC(sizeof(servlistpendingitem));

			if (pNewItem)
			{ // move the remaining operations
#ifdef _DEBUG
				if (pItem->nType == ITEM_PENDING_CONTACT)
					debugLogA("Server-List: Resuming contact %x operation.", pItem->hContact);
				else
					debugLogA("Server-List: Resuming group \"%s\" operation.", pItem->szGroup);
#endif

				pNewItem->nType = pItem->nType;
				pNewItem->hContact = pItem->hContact;
				pNewItem->szGroup = null_strdup(pItem->szGroup);
				pNewItem->wContactID = pItem->wContactID;
				pNewItem->wGroupID = pItem->wGroupID;
				pNewItem->operationsCount = pItem->operationsCount - 1;
				pNewItem->operations = (servlistpendingoperation*)SAFE_MALLOC(pNewItem->operationsCount * sizeof(servlistpendingoperation));
				memcpy(pNewItem->operations, pItem->operations + 1, pNewItem->operationsCount * sizeof(servlistpendingoperation));
				pItem->operationsCount = 1;

				servlistPendingAddItem(pNewItem);
				// clear the flag
				pItem->operations[0].flags &= ~SPOF_AUTO_CREATE_ITEM;
			}
		}
	}
#ifdef _DEBUG
	else
		debugLogA("Server-List Error: Trying to remove non-existing pending %s.", nType == ITEM_PENDING_CONTACT ? "contact" : "group");
#endif

	return pItem;
}


void CIcqProto::servlistPendingAddContactOperation(MCONTACT hContact, LPARAM param, PENDING_CONTACT_CALLBACK callback, DWORD flags)
{ // add postponed operation (add contact, update contact, regroup resume, etc.)
	// - after contact is added
	int iItem;
	servlistpendingitem *pItem = NULL;

	icq_lock l(servlistMutex);

	if ((iItem = servlistPendingFindItem(ITEM_PENDING_CONTACT, hContact, NULL)) != -1)
		pItem = servlistPendingList[iItem];

	if (pItem)
	{
		int iOperation = pItem->operationsCount++;

		pItem->operations = (servlistpendingoperation*)SAFE_REALLOC(pItem->operations, pItem->operationsCount * sizeof(servlistpendingoperation));
		pItem->operations[iOperation].param = param;
		pItem->operations[iOperation].callback = (PENDING_GROUP_CALLBACK)callback;
		pItem->operations[iOperation].flags = flags;
	}
	else
	{
		debugLogA("Server-List Error: Trying to add pending operation to a non existing contact.");
	}
}


void CIcqProto::servlistPendingAddGroupOperation(const char *pszGroup, LPARAM param, PENDING_GROUP_CALLBACK callback, DWORD flags)
{ // add postponed operation - after group is added
	int iItem;
	servlistpendingitem *pItem = NULL;

	icq_lock l(servlistMutex);

	if ((iItem = servlistPendingFindItem(ITEM_PENDING_GROUP, NULL, pszGroup)) != -1)
		pItem = servlistPendingList[iItem];

	if (pItem)
	{
		int iOperation = pItem->operationsCount++;

		pItem->operations = (servlistpendingoperation*)SAFE_REALLOC(pItem->operations, pItem->operationsCount * sizeof(servlistpendingoperation));
		pItem->operations[iOperation].param = param;
		pItem->operations[iOperation].callback = callback;
		pItem->operations[iOperation].flags = flags;
	}
	else
	{
		debugLogA("Server-List Error: Trying to add pending operation to a non existing group.");
	}
}


int CIcqProto::servlistPendingAddContact(MCONTACT hContact, WORD wContactID, WORD wGroupID, LPARAM param, PENDING_CONTACT_CALLBACK callback, int bDoInline, LPARAM operationParam, PENDING_CONTACT_CALLBACK operationCallback)
{
	int iItem;
	servlistpendingitem *pItem = NULL;

	servlistMutex->Enter();

	if ((iItem = servlistPendingFindItem(ITEM_PENDING_CONTACT, hContact, NULL)) != -1)
		pItem = servlistPendingList[iItem];

	if (pItem)
	{
#ifdef _DEBUG
		debugLogA("Server-List: Pending contact %x already in list; adding as operation.", hContact);
#endif
		servlistPendingAddContactOperation(hContact, param, callback, SPOF_AUTO_CREATE_ITEM);

		if (operationCallback)
			servlistPendingAddContactOperation(hContact, operationParam, operationCallback, 0);

		servlistMutex->Leave();

		return 0; // Pending
	}

#ifdef _DEBUG
	debugLogA("Server-List: Starting contact %x operation.", hContact);
#endif

	pItem = (servlistpendingitem *)SAFE_MALLOC(sizeof(servlistpendingitem));
	pItem->nType = ITEM_PENDING_CONTACT;
	pItem->hContact = hContact;
	pItem->wContactID = wContactID;
	pItem->wGroupID = wGroupID;

	servlistPendingAddItem(pItem);

	if (operationCallback)
		servlistPendingAddContactOperation(hContact, operationParam, operationCallback, 0);

	servlistMutex->Leave();

	if (bDoInline)
	{ // not postponed, called directly if requested
		(this->*callback)(hContact, wContactID, wGroupID, param, PENDING_RESULT_INLINE);
	}

	return 1; // Ready
}


int CIcqProto::servlistPendingAddGroup(const char *pszGroup, WORD wGroupID, LPARAM param, PENDING_GROUP_CALLBACK callback, int bDoInline, LPARAM operationParam, PENDING_GROUP_CALLBACK operationCallback)
{
	int iItem;
	servlistpendingitem *pItem = NULL;

	servlistMutex->Enter();

	if ((iItem = servlistPendingFindItem(ITEM_PENDING_GROUP, NULL, pszGroup)) != -1)
		pItem = servlistPendingList[iItem];

	if (pItem)
	{
#ifdef _DEBUG
		debugLogA("Server-List: Pending group \"%s\" already in list; adding as operation.", pszGroup);
#endif
		servlistPendingAddGroupOperation(pszGroup, param, callback, SPOF_AUTO_CREATE_ITEM);

		if (operationCallback)
			servlistPendingAddGroupOperation(pszGroup, operationParam, operationCallback, 0);

		servlistMutex->Leave();

		return 0; // Pending
	}

#ifdef _DEBUG
	debugLogA("Server-List: Starting group \"%s\" operation.", pszGroup);
#endif

	pItem = (servlistpendingitem *)SAFE_MALLOC(sizeof(servlistpendingitem));
	pItem->nType = ITEM_PENDING_GROUP;
	pItem->szGroup = null_strdup(pszGroup);
	pItem->wGroupID = wGroupID;

	servlistPendingAddItem(pItem);

	if (operationCallback)
		servlistPendingAddGroupOperation(pszGroup, operationParam, operationCallback, 0);

	servlistMutex->Leave();

	if (bDoInline)
	{ // not postponed, called directly if requested
		(this->*callback)(pszGroup, wGroupID, param, PENDING_RESULT_INLINE);
	}

	return 1; // Ready
}


void CIcqProto::servlistPendingRemoveContact(MCONTACT hContact, WORD wContactID, WORD wGroupID, int nResult)
{
#ifdef _DEBUG
	debugLogA("Server-List: %s contact %x operation.", (nResult != PENDING_RESULT_PURGE) ? "Ending" : "Purging", hContact);
#endif

	servlistpendingitem *pItem = servlistPendingRemoveItem(ITEM_PENDING_CONTACT, hContact, NULL);

	if (pItem)
	{ // process pending operations
		if (pItem->operations)
		{
			for (int i = 0; i < pItem->operationsCount; i++)
			{
				int nCallbackState = (this->*(PENDING_CONTACT_CALLBACK)(pItem->operations[i].callback))(hContact, wContactID, wGroupID, pItem->operations[i].param, nResult);

				if (nResult != PENDING_RESULT_PURGE && nCallbackState == CALLBACK_RESULT_POSTPONE)
				{ // any following pending operations cannot be processed now, move them to the new pending contact
					for (int j = i + 1; j < pItem->operationsCount; j++)
						servlistPendingAddContactOperation(hContact, pItem->operations[j].param, (PENDING_CONTACT_CALLBACK)(pItem->operations[j].callback), pItem->operations[j].flags);
					break;
				}
				else if (nCallbackState == CALLBACK_RESULT_PURGE)
				{ // purge all following operations - fatal failure occured
					nResult = PENDING_RESULT_PURGE;
				}
			}
			SAFE_FREE((void**)&pItem->operations);
		}
		// release item's memory
		SAFE_FREE((void**)&pItem);
	}
	else
		debugLogA("Server-List Error: Trying to remove a non existing pending contact.");
}


void CIcqProto::servlistPendingRemoveGroup(const char *pszGroup, WORD wGroupID, int nResult)
{
#ifdef _DEBUG
	debugLogA("Server-List: %s group \"%s\" operation.", (nResult != PENDING_RESULT_PURGE) ? "Ending" : "Purging", pszGroup);
#endif

	servlistpendingitem *pItem = servlistPendingRemoveItem(ITEM_PENDING_GROUP, NULL, pszGroup);

	if (pItem)
	{ // process pending operations
		if (pItem->operations)
		{
			for (int i = 0; i < pItem->operationsCount; i++)
			{
				int nCallbackState = (this->*pItem->operations[i].callback)(pItem->szGroup, wGroupID, pItem->operations[i].param, nResult);

				if (nResult != PENDING_RESULT_PURGE && nCallbackState == CALLBACK_RESULT_POSTPONE)
				{ // any following pending operations cannot be processed now, move them to the new pending group
					for (int j = i + 1; j < pItem->operationsCount; j++)
						servlistPendingAddGroupOperation(pItem->szGroup, pItem->operations[j].param, pItem->operations[j].callback, pItem->operations[j].flags);
					break;
				}
				else if (nCallbackState == CALLBACK_RESULT_PURGE)
				{ // purge all following operations - fatal failure occured
					nResult = PENDING_RESULT_PURGE;
				}
			}
			SAFE_FREE((void**)&pItem->operations);
		}
		// release item's memory
		SAFE_FREE((void**)&pItem->szGroup);
		SAFE_FREE((void**)&pItem);
	}
	else
		debugLogA("Server-List Error: Trying to remove a non existing pending group.");
}


// Remove All pending operations
void CIcqProto::servlistPendingFlushOperations()
{
	icq_lock l(servlistMutex);

	for (int i = servlistPendingCount; i; i--)
	{ // purge all items
		servlistpendingitem *pItem = servlistPendingList[i - 1];

		if (pItem->nType == ITEM_PENDING_CONTACT)
			servlistPendingRemoveContact(pItem->hContact, 0, 0, PENDING_RESULT_PURGE);
		else if (pItem->nType == ITEM_PENDING_GROUP)
			servlistPendingRemoveGroup(pItem->szGroup, 0, PENDING_RESULT_PURGE);
	}
	// release the list completely
	SAFE_FREE((void**)&servlistPendingList);
	servlistPendingCount = 0;
	servlistPendingSize = 0;
}

// END OF SERVER-LIST PENDING OPERATIONS
////


// used for adding new contacts to list - sync with visible items
void CIcqProto::AddJustAddedContact(MCONTACT hContact)
{
	icq_lock l(servlistMutex);

	if (nJustAddedCount >= nJustAddedSize)
	{
		nJustAddedSize += 10;
		pdwJustAddedList = (MCONTACT*)SAFE_REALLOC(pdwJustAddedList, nJustAddedSize * sizeof(MCONTACT));
	}

	pdwJustAddedList[nJustAddedCount] = hContact;
	nJustAddedCount++;  
}


// was the contact added during this serv-list load
BOOL CIcqProto::IsContactJustAdded(MCONTACT hContact)
{
	icq_lock l(servlistMutex);

	if (pdwJustAddedList)
	{
		for (int i = 0; i<nJustAddedCount; i++)
		{
			if (pdwJustAddedList[i] == hContact)
				return TRUE;
		}
	}

	return FALSE;
}


void CIcqProto::FlushJustAddedContacts()
{
	icq_lock l(servlistMutex);

	SAFE_FREE((void**)&pdwJustAddedList);
	nJustAddedSize = 0;
	nJustAddedCount = 0;
}


// Add a server ID to the list of reserved IDs.
// To speed up the process, no checks is done, if
// you try to reserve an ID twice, it will be added again.
// You should call CheckServerID before reserving an ID.
void CIcqProto::ReserveServerID(WORD wID, int bGroupType, int bFlags)
{
	servlistMutex->Enter();
	if (nServerIDListCount >= nServerIDListSize)
	{
		nServerIDListSize += 100;
		pdwServerIDList = (DWORD*)SAFE_REALLOC(pdwServerIDList, nServerIDListSize * sizeof(DWORD));
	}

	pdwServerIDList[nServerIDListCount] = wID | (bGroupType & 0x00FF0000) | (bFlags & 0xFF000000);
	nServerIDListCount++;
	servlistMutex->Leave();

	if (!bIsSyncingCL)
		StoreServerIDs();
}


// Remove a server ID from the list of reserved IDs.
// Used for deleting contacts and other modifications.
void CIcqProto::FreeServerID(WORD wID, int bGroupType)
{
	DWORD dwId = wID | (bGroupType & 0x00FF0000);

	icq_lock l(servlistMutex);

	if (pdwServerIDList)
	{
		for (int i = 0; i<nServerIDListCount; i++)
		{
			if ((pdwServerIDList[i] & 0x00FFFFFF) == dwId)
			{ // we found it, so remove
				for (int j = i+1; j<nServerIDListCount; j++)
					pdwServerIDList[j-1] = pdwServerIDList[j];

				nServerIDListCount--;
			}
		}
	}
}


// Returns true if dwID is reserved
BOOL CIcqProto::CheckServerID(WORD wID, unsigned int wCount)
{
	icq_lock l(servlistMutex);

	if (pdwServerIDList)
	{
		for (int i = 0; i<nServerIDListCount; i++)
		{
			if (((pdwServerIDList[i] & 0xFFFF) >= wID) && ((pdwServerIDList[i] & 0xFFFF) <= wID + wCount))
				return TRUE;
		}
	}

	return FALSE;
}

void CIcqProto::FlushServerIDs()
{
	icq_lock l(servlistMutex);

	SAFE_FREE((void**)&pdwServerIDList);
	nServerIDListCount = 0;
	nServerIDListSize = 0;
}

/////////////////////////////////////////////////////////////////////////////////////////

struct GroupReserveIdsEnumParam
{
	CIcqProto *ppro;
	char *szModule;
};

static int GroupReserveIdsEnumProc(const char *szSetting,LPARAM lParam)
{ 
	if (szSetting && strlennull(szSetting)<5)
	{ 
		// it is probably server group
		GroupReserveIdsEnumParam *param = (GroupReserveIdsEnumParam*)lParam;
		char val[MAX_PATH+2]; // dummy
		if (db_get_static(0, param->szModule, szSetting, val, MAX_PATH))
			if (db_get_static_utf(0, param->szModule, szSetting, val, MAX_PATH))
				return 0; // we failed also, invalid setting

		param->ppro->ReserveServerID((WORD)strtoul(szSetting, NULL, 0x10), SSIT_GROUP, 0);
#ifdef _DEBUG
		param->ppro->debugLogA("Loaded group %u:'%s'", strtoul(szSetting, NULL, 0x10), val);
#endif
	}
	return 0;
}

/////////////////////////////////////////////////////////////////////////////////////////
// Load all known server IDs from DB to list
void CIcqProto::LoadServerIDs()
{
	WORD wSrvID;
	int nGroups = 0, nContacts = 0, nPermits = 0, nDenys = 0, nIgnores = 0, nUnhandled = 0;

	servlistMutex->Enter();
	if (wSrvID = getWord(DBSETTING_SERVLIST_AVATAR, 0))
		ReserveServerID(wSrvID, SSIT_ITEM, 0);
	if (wSrvID = getWord(DBSETTING_SERVLIST_PHOTO, 0))
		ReserveServerID(wSrvID, SSIT_ITEM, 0);
	if (wSrvID = getWord(DBSETTING_SERVLIST_PRIVACY, 0))
		ReserveServerID(wSrvID, SSIT_ITEM, 0);
	if (wSrvID = getWord(DBSETTING_SERVLIST_METAINFO, 0))
		ReserveServerID(wSrvID, SSIT_ITEM, 0);
	if (wSrvID = getWord("SrvImportID", 0))
		ReserveServerID(wSrvID, SSIT_ITEM, 0);

	int nStart = nServerIDListCount;

	char szModule[MAX_PATH];
	mir_snprintf(szModule, SIZEOF(szModule), "%sSrvGroups", m_szModuleName);
	GroupReserveIdsEnumParam param = { this, szModule };

	DBCONTACTENUMSETTINGS dbces = { 0 };
	dbces.pfnEnumProc = &GroupReserveIdsEnumProc;
	dbces.szModule = szModule;
	dbces.lParam = (LPARAM)&param;
	CallService(MS_DB_CONTACT_ENUMSETTINGS, 0, (LPARAM)&dbces);

	nGroups = nServerIDListCount - nStart;

	MCONTACT hContact = db_find_first(m_szModuleName);

	while (hContact)
	{ // search all our contacts, reserve their server IDs
		if (wSrvID = getWord(hContact, DBSETTING_SERVLIST_ID, 0))
		{
			ReserveServerID(wSrvID, SSIT_ITEM, 0);
			nContacts++;
		}
		if (wSrvID = getWord(hContact, DBSETTING_SERVLIST_DENY, 0))
		{
			ReserveServerID(wSrvID, SSIT_ITEM, 0);
			nDenys++;
		}
		if (wSrvID = getWord(hContact, DBSETTING_SERVLIST_PERMIT, 0))
		{
			ReserveServerID(wSrvID, SSIT_ITEM, 0);
			nPermits++;
		}
		if (wSrvID = getWord(hContact, DBSETTING_SERVLIST_IGNORE, 0))
		{
			ReserveServerID(wSrvID, SSIT_ITEM, 0);
			nIgnores++;
		}

		hContact = db_find_next(hContact, m_szModuleName);
	}
	servlistMutex->Leave();

	DBVARIANT dbv = {0};
	if (!getSetting(NULL, DBSETTING_SERVLIST_UNHANDLED, &dbv))
	{
		int dataLen = dbv.cpbVal;
		BYTE *pData = dbv.pbVal;

		while (dataLen >= 4)
		{
			BYTE bGroupType;
			BYTE bFlags;

			unpackLEWord(&pData, &wSrvID);
			unpackByte(&pData, &bGroupType);
			unpackByte(&pData, &bFlags);

			ReserveServerID(wSrvID, bGroupType, bFlags); 
			dataLen -= 4;
			nUnhandled++;
		}

		db_free(&dbv);
	}

	debugLogA("Loaded SSI: %d contacts, %d groups, %d permit, %d deny, %d ignore, %d unknown items.", nContacts, nGroups, nPermits, nDenys, nIgnores, nUnhandled);
}


void CIcqProto::StoreServerIDs() /// TODO: allow delayed
{
	BYTE *pUnhandled = NULL;
	int cbUnhandled = 0;

	servlistMutex->Enter();
	if (pdwServerIDList)
		for (int i = 0; i<nServerIDListCount; i++)
			if ((pdwServerIDList[i] & 0xFF000000) == SSIF_UNHANDLED)
			{
				ppackLEWord(&pUnhandled, &cbUnhandled, pdwServerIDList[i] & 0xFFFF);
				ppackByte(&pUnhandled, &cbUnhandled, (pdwServerIDList[i] & 0x00FF0000) >> 0x10);
				ppackByte(&pUnhandled, &cbUnhandled, (pdwServerIDList[i] & 0xFF000000) >> 0x18);
			}
			servlistMutex->Leave();

			if (pUnhandled)
				setSettingBlob(NULL, DBSETTING_SERVLIST_UNHANDLED, pUnhandled, cbUnhandled);
			else
				delSetting(DBSETTING_SERVLIST_UNHANDLED);

			SAFE_FREE((void**)&pUnhandled);
}


// Generate server ID with wCount IDs free after it, for sub-groups.
WORD CIcqProto::GenerateServerID(int bGroupType, int bFlags, int wCount)
{
	WORD wId;

	while (TRUE)
	{
		// Randomize a new ID
		// Max value is probably 0x7FFF, lowest value is probably 0x0001 (generated by Icq2Go)
		// We use range 0x1000-0x7FFF.
		wId = (WORD)RandRange(0x1000, 0x7FFF);

		if (!CheckServerID(wId, wCount))
			break;
	}

	ReserveServerID(wId, bGroupType, bFlags);

	return wId;
}


/***********************************************
*
*  --- Low-level packet sending functions ---
*
*/

struct doubleServerItemObject
{
	WORD wAction;
	icq_packet packet;
};

DWORD CIcqProto::icq_sendServerItem(DWORD dwCookie, WORD wAction, WORD wGroupId, WORD wItemId, const char *szName, BYTE *pTLVs, int nTlvLength, WORD wItemType, DWORD dwOperation, DWORD dwTimeout, void **doubleObject)
{ // generic packet
	icq_packet packet;
	int nNameLen;
	WORD wTLVlen = (WORD)nTlvLength;

	// Prepare item name length
	nNameLen = strlennull(szName);

	// Build the packet
	serverPacketInit(&packet, (WORD)(nNameLen + 20 + wTLVlen));
	packFNACHeader(&packet, ICQ_LISTS_FAMILY, wAction, 0, dwCookie);
	packWord(&packet, (WORD)nNameLen);
	if (nNameLen) 
		packBuffer(&packet, (LPBYTE)szName, (WORD)nNameLen);
	packWord(&packet, wGroupId);
	packWord(&packet, wItemId);   
	packWord(&packet, wItemType); 
	packWord(&packet, wTLVlen);
	if (wTLVlen)
		packBuffer(&packet, pTLVs, wTLVlen);

	if (!doubleObject)
	{ // Send the packet and return the cookie
		servlistPostPacket(&packet, dwCookie, dwOperation | wAction, dwTimeout);
	}
	else
	{
		if (*doubleObject)
		{ // Send both packets and return the cookie
			doubleServerItemObject* helper = (doubleServerItemObject*)*doubleObject;

			servlistPostPacketDouble(&helper->packet, dwCookie, dwOperation | helper->wAction, dwTimeout, &packet, wAction);
			SAFE_FREE(doubleObject);
		}
		else
		{ // Create helper object, return the cookie
			doubleServerItemObject* helper = (doubleServerItemObject*)SAFE_MALLOC(sizeof(doubleServerItemObject));

			if (helper)
			{
				helper->wAction = wAction;
				memcpy(&helper->packet, &packet, sizeof(icq_packet));
				*doubleObject = helper;
			}
			else // memory alloc failed
				return 0;
		}
	}

	// Force reload of server-list after change
	setWord("SrvRecordCount", 0);

	return dwCookie;
}


DWORD CIcqProto::icq_sendServerContact(MCONTACT hContact, DWORD dwCookie, WORD wAction, WORD wGroupId, WORD wContactId, DWORD dwOperation, DWORD dwTimeout, void **doubleObject)
{
	DWORD dwUin;
	uid_str szUid;
	icq_packet pBuffer;
	char *szNick = NULL, *szNote = NULL;
	BYTE *pData = NULL, *pMetaToken = NULL, *pMetaTime = NULL;
	int nNickLen, nNoteLen, nDataLen = 0, nMetaTokenLen = 0, nMetaTimeLen = 0;
	WORD wTLVlen;
	BYTE bAuth;
	int bDataTooLong = FALSE;

	// Prepare UID
	if (getContactUid(hContact, &dwUin, &szUid))
	{
		debugLogA("Buddy upload failed (UID missing).");
		return 0;
	}

	bAuth = getByte(hContact, "Auth", 0);
	szNick = getSettingStringUtf(hContact, "CList", "MyHandle", NULL);
	szNote = getSettingStringUtf(hContact, "UserInfo", "MyNotes", NULL);

	DBVARIANT dbv;

	if (!getSetting(hContact, DBSETTING_METAINFO_TOKEN, &dbv))
	{
		nMetaTokenLen = dbv.cpbVal;
		pMetaToken = (BYTE*)_alloca(dbv.cpbVal);
		memcpy(pMetaToken, dbv.pbVal, dbv.cpbVal);

		db_free(&dbv);
	}
	if (!getSetting(hContact, DBSETTING_METAINFO_TIME, &dbv))
	{
		nMetaTimeLen = dbv.cpbVal;
		pMetaTime = (BYTE*)_alloca(dbv.cpbVal);
		for (int i = 0; i < dbv.cpbVal; i++)
			pMetaTime[i] = dbv.pbVal[dbv.cpbVal - i - 1];

		db_free(&dbv);
	}

	if (!getSetting(hContact, DBSETTING_SERVLIST_DATA, &dbv))
	{ // read additional server item data
		nDataLen = dbv.cpbVal;
		pData = (BYTE*)_alloca(nDataLen);
		memcpy(pData, dbv.pbVal, nDataLen);

		db_free(&dbv);
	}

	nNickLen = strlennull(szNick);
	nNoteLen = strlennull(szNote);

	// Limit the strings
	if (nNickLen > MAX_SSI_TLV_NAME_SIZE)
	{
		bDataTooLong = TRUE;
		nNickLen = null_strcut(szNick, MAX_SSI_TLV_NAME_SIZE);
	}
	if (nNoteLen > MAX_SSI_TLV_COMMENT_SIZE)
	{
		bDataTooLong = TRUE;
		nNoteLen = null_strcut(szNote, MAX_SSI_TLV_COMMENT_SIZE);
	}
	if (bDataTooLong)
	{ // Inform the user
		/// TODO: do something with this for Manage Server-List dialog.
		if (wAction != ICQ_LISTS_REMOVEFROMLIST) // do not report this when removing from list
			icq_LogMessage(LOG_WARNING, LPGEN("The contact's information was too big and was truncated."));
	}

	// Build the packet
	wTLVlen = (nNickLen?4+nNickLen:0) + (nNoteLen?4+nNoteLen:0) + (bAuth?4:0) + nDataLen + (nMetaTokenLen?4+nMetaTokenLen:0) + (nMetaTimeLen?4+nMetaTimeLen:0);

	// Initialize our handy data buffer
	pBuffer.wPlace = 0;
	pBuffer.pData = (BYTE *)_alloca(wTLVlen);
	pBuffer.wLen = wTLVlen;

	if (nNickLen)
		packTLV(&pBuffer, SSI_TLV_NAME, (WORD)nNickLen, (LPBYTE)szNick);  // Nickname TLV

	if (nNoteLen)
		packTLV(&pBuffer, SSI_TLV_COMMENT, (WORD)nNoteLen, (LPBYTE)szNote);  // Comment TLV

	if (nMetaTokenLen)
		packTLV(&pBuffer, SSI_TLV_METAINFO_TOKEN, (WORD)nMetaTokenLen, pMetaToken);

	if (nMetaTimeLen)
		packTLV(&pBuffer, SSI_TLV_METAINFO_TIME, (WORD)nMetaTimeLen, pMetaTime);

	if (pData)
		packBuffer(&pBuffer, pData, (WORD)nDataLen);

	if (bAuth) // icq5 gives this as last TLV
		packDWord(&pBuffer, 0x00660000);  // "Still waiting for auth" TLV

	SAFE_FREE((void**)&szNick);
	SAFE_FREE((void**)&szNote);

	return icq_sendServerItem(dwCookie, wAction, wGroupId, wContactId, strUID(dwUin, szUid), pBuffer.pData, wTLVlen, SSI_ITEM_BUDDY, dwOperation, dwTimeout, doubleObject);
}


DWORD CIcqProto::icq_sendSimpleItem(DWORD dwCookie, WORD wAction, DWORD dwUin, char* szUID, WORD wGroupId, WORD wItemId, WORD wItemType, DWORD dwOperation, DWORD dwTimeout)
{ // for privacy items
	return icq_sendServerItem(dwCookie, wAction, wGroupId, wItemId, strUID(dwUin, szUID), NULL, 0, wItemType, dwOperation, dwTimeout, NULL);
}


DWORD CIcqProto::icq_sendServerGroup(DWORD dwCookie, WORD wAction, WORD wGroupId, const char *szName, void *pContent, int cbContent, DWORD dwOperationFlags)
{
	WORD wTLVlen;
	icq_packet pBuffer; // I reuse the ICQ packet type as a generic buffer
	// I should be ashamed! ;)

	if (strlennull(szName) == 0 && wGroupId != 0)
	{
		debugLogA("Group upload failed (GroupName missing).");
		return 0; // without name we could not change the group
	}

	// Calculate buffer size
	wTLVlen = (cbContent?4+cbContent:0);

	// Initialize our handy data buffer
	pBuffer.wPlace = 0;
	pBuffer.pData = (BYTE *)_alloca(wTLVlen);
	pBuffer.wLen = wTLVlen;

	if (wTLVlen)
		packTLV(&pBuffer, SSI_TLV_SUBITEMS, (WORD)cbContent, (LPBYTE)pContent);  // Groups TLV

	return icq_sendServerItem(dwCookie, wAction, wGroupId, 0, szName, pBuffer.pData, wTLVlen, SSI_ITEM_GROUP, SSOP_GROUP_ACTION | dwOperationFlags, 400, NULL);
}


DWORD CIcqProto::icq_modifyServerPrivacyItem(MCONTACT hContact, DWORD dwUin, char *szUid, WORD wAction, DWORD dwOperation, WORD wItemId, WORD wType)
{
	cookie_servlist_action *ack = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action));
	DWORD dwCookie;

	if (ack)
	{
		ack->dwAction = dwOperation; // remove privacy item
		ack->hContact = hContact;
		ack->wContactId = wItemId;

		dwCookie = AllocateCookie(CKT_SERVERLIST, wAction, hContact, ack);
	}
	else // cookie failed
		return 0;

	return icq_sendSimpleItem(dwCookie, wAction, dwUin, szUid, 0, wItemId, wType, SSOP_ITEM_ACTION, 400);
}


DWORD CIcqProto::icq_removeServerPrivacyItem(MCONTACT hContact, DWORD dwUin, char *szUid, WORD wItemId, WORD wType)
{
	return icq_modifyServerPrivacyItem(hContact, dwUin, szUid, ICQ_LISTS_REMOVEFROMLIST, SSA_PRIVACY_REMOVE, wItemId, wType);
}


DWORD CIcqProto::icq_addServerPrivacyItem(MCONTACT hContact, DWORD dwUin, char *szUid, WORD wItemId, WORD wType)
{
	return icq_modifyServerPrivacyItem(hContact, dwUin, szUid, ICQ_LISTS_ADDTOLIST, SSA_PRIVACY_ADD, wItemId, wType);
}

/*****************************************
*
*     --- Contact DB Utilities ---
*
*/


/// TODO: do not check by plugin version, check by ServListStructures version!
int CIcqProto::IsServerGroupsDefined()
{
	int iRes = 1;

	if (getDword("Version", 0) < 0x00030608)
	{ // group cache & linking data too old, flush, reload from server
		char szModule[MAX_PATH];

		// flush obsolete linking data
		mir_snprintf(szModule, SIZEOF(szModule), "%sGroups", m_szModuleName);
		CallService(MS_DB_MODULE_DELETE, 0, (LPARAM)szModule);

		iRes = 0; // no groups defined, or older version
	}
	// store our current version
	setDword("Version", ICQ_PLUG_VERSION & 0x00FFFFFF);

	return iRes;
}


void CIcqProto::FlushSrvGroupsCache()
{
	char szModule[MAX_PATH];

	mir_snprintf(szModule, SIZEOF(szModule), "%sSrvGroups", m_szModuleName);
	CallService(MS_DB_MODULE_DELETE, 0, (LPARAM)szModule);
}


// Look thru DB and collect all ContactIDs from a group
void* CIcqProto::collectBuddyGroup(WORD wGroupID, int *count)
{
	WORD* buf = NULL;
	int cnt = 0;
	MCONTACT hContact;
	WORD wItemID;

	hContact = db_find_first(m_szModuleName);

	while (hContact)
	{ // search all contacts
		if (wGroupID == getWord(hContact, DBSETTING_SERVLIST_GROUP, 0))
		{ // add only buddys from specified group
			wItemID = getWord(hContact, DBSETTING_SERVLIST_ID, 0);

			if (wItemID)
			{ // valid ID, add
				cnt++;
				buf = (WORD*)SAFE_REALLOC(buf, cnt*sizeof(WORD));
				buf[cnt-1] = wItemID;
				if (!count) break;
			}
		}

		hContact = db_find_next(hContact, m_szModuleName);
	}

	if (count)
		*count = cnt<<1; // we return size in bytes
	return buf;
}


// Look thru DB and collect all GroupIDs
void* CIcqProto::collectGroups(int *count)
{
	WORD* buf = NULL;
	int cnt = 0;
	int i;
	MCONTACT hContact;
	WORD wGroupID;

	hContact = db_find_first(m_szModuleName);

	while (hContact)
	{ // search all contacts
		if (wGroupID = getWord(hContact, DBSETTING_SERVLIST_GROUP, 0))
		{ // add only valid IDs
			for (i = 0; i<cnt; i++)
			{ // check for already added ids
				if (buf[i] == wGroupID) break;
			}

			if (i == cnt)
			{ // not preset, add
				cnt++;
				buf = (WORD*)SAFE_REALLOC(buf, cnt*sizeof(WORD));
				buf[i] = wGroupID;
			}
		}

		hContact = db_find_next(hContact, m_szModuleName);
	}

	*count = cnt<<1;
	return buf;
}


static int GroupLinksEnumProc(const char *szSetting,LPARAM lParam)
{
	// check link target, add if match
	if (db_get_w(NULL, ((char**)lParam)[2], szSetting, 0) == (WORD)((char**)lParam)[1])
	{
		char** block = (char**)SAFE_MALLOC(2*sizeof(char*));
		block[1] = null_strdup(szSetting);
		block[0] = ((char**)lParam)[0];
		((char**)lParam)[0] = (char*)block;
	}
	return 0;
}

void CIcqProto::removeGroupPathLinks(WORD wGroupID)
{ // remove miranda grouppath links targeting to this groupid
	char szModule[MAX_PATH];
	char* pars[3];

	mir_snprintf(szModule, SIZEOF(szModule), "%sGroups", m_szModuleName);

	pars[0] = NULL;
	pars[1] = (char*)wGroupID;
	pars[2] = szModule;

	DBCONTACTENUMSETTINGS dbces = { 0 };
	dbces.pfnEnumProc = &GroupLinksEnumProc;
	dbces.szModule = szModule;
	dbces.lParam = (LPARAM)pars;

	if (!CallService(MS_DB_CONTACT_ENUMSETTINGS, 0, (LPARAM)&dbces))
	{ // we found some links, remove them
		char** list = (char**)pars[0];
		while (list)
		{
			void* bet;

			db_unset(NULL, szModule, list[1]);
			SAFE_FREE((void**)&list[1]);
			bet = list;
			list = (char**)list[0];
			SAFE_FREE((void**)&bet);
		}
	}
}


char *CIcqProto::getServListGroupName(WORD wGroupID)
{
	char szModule[MAX_PATH];
	char szGroup[16];

	if (!wGroupID)
	{
		debugLogA("Warning: Cannot get group name (Group ID missing)!");
		return NULL;
	}

	mir_snprintf(szModule, SIZEOF(szModule), "%sSrvGroups", m_szModuleName);
	_itoa(wGroupID, szGroup, 0x10);

	if (!CheckServerID(wGroupID, 0))
	{ // check if valid id, if not give empty and remove
		debugLogA("Removing group %u from cache...", wGroupID);
		db_unset(NULL, szModule, szGroup);
		return NULL;
	}

	return getSettingStringUtf(NULL, szModule, szGroup, NULL);
}


void CIcqProto::setServListGroupName(WORD wGroupID, const char *szGroupName)
{
	char szModule[MAX_PATH];
	char szGroup[16];

	if (!wGroupID)
	{
		debugLogA("Warning: Cannot set group name (Group ID missing)!");
		return;
	}

	mir_snprintf(szModule, SIZEOF(szModule), "%sSrvGroups", m_szModuleName);
	_itoa(wGroupID, szGroup, 0x10);

	if (szGroupName)
		db_set_utf(NULL, szModule, szGroup, szGroupName);
	else
	{
		db_unset(NULL, szModule, szGroup);
		removeGroupPathLinks(wGroupID);
	}
	return;
}


WORD CIcqProto::getServListGroupLinkID(const char *szPath)
{
	char szModule[MAX_PATH];
	WORD wGroupId;

	mir_snprintf(szModule, SIZEOF(szModule), "%sGroups", m_szModuleName);

	wGroupId = db_get_w(NULL, szModule, szPath, 0);

	if (wGroupId && !CheckServerID(wGroupId, 0))
	{ // known, check if still valid, if not remove
		debugLogA("Removing group \"%s\" from cache...", szPath);
		db_unset(NULL, szModule, szPath);
		wGroupId = 0;
	}

	return wGroupId;
}


void CIcqProto::setServListGroupLinkID(const char *szPath, WORD wGroupID)
{
	char szModule[MAX_PATH];

	mir_snprintf(szModule, SIZEOF(szModule), "%sGroups", m_szModuleName);

	if (wGroupID)
		db_set_w(NULL, szModule, szPath, wGroupID);
	else
		db_unset(NULL, szModule, szPath);
}

// determine if the specified clist group path exists
//!! this function is not thread-safe due to the use of cli->pfnGetGroupName()
int CIcqProto::getCListGroupExists(const char *szGroup)
{
	if (!szGroup)
		return 0;

	int size = strlennull(szGroup) + 2;
	TCHAR *tszGroup = (TCHAR*)_alloca(size * sizeof(TCHAR));

	if (utf8_to_tchar_static(szGroup, tszGroup, size))
		for (int i = 1; TRUE; i++) {
			TCHAR *tszGroupName = (TCHAR*)pcli->pfnGetGroupName(i, NULL);
			if (!tszGroupName)
				break;

			// we have found the group
			if (!_tcscmp(tszGroup, tszGroupName))
				return i;
		}

	return 0;
}


int CIcqProto::moveContactToCListGroup(MCONTACT hContact, const char *szGroup)
{
	HANDLE hGroup = Clist_CreateGroup(0, ptrT( mir_utf8decodeT(szGroup)));

	if (ServiceExists(MS_CLIST_CONTACTCHANGEGROUP))
		return CallService(MS_CLIST_CONTACTCHANGEGROUP, hContact, (LPARAM)hGroup);
	else /// TODO: is this neccessary ?
		return db_set_utf(hContact, "CList", "Group", szGroup);
}


// utility function which counts > on start of a server group name
static int countGroupNameLevel(const char *szGroupName)
{
	int nNameLen = strlennull(szGroupName);
	int i = 0;

	while (i<nNameLen)
	{
		if (szGroupName[i] != '>')
			return i;

		i++;
	}
	return -1;
}

static int countCListGroupLevel(const char *szClistName)
{
	int nNameLen = strlennull(szClistName);
	int i, level = 0;

	for (i = 0; i < nNameLen; i++)
		if (szClistName[i] == '\\') level++;

	return level;
}

int CIcqProto::getServListGroupLevel(WORD wGroupId)
{
	char *szGroupName = getServListGroupName(wGroupId);
	int cnt = -1;

	if (szGroupName)
	{ // groupid is valid count group name level
		if (m_bSsiSimpleGroups)
			cnt = countCListGroupLevel(szGroupName);
		else
			cnt = countGroupNameLevel(szGroupName);

		SAFE_FREE((void**)&szGroupName);
	}

	return cnt;
}


// demangle group path
char *CIcqProto::getServListGroupCListPath(WORD wGroupId)
{
	char *szGroup = NULL;

	if (szGroup = getServListGroupName(wGroupId))
	{ // this groupid is valid
		if (!m_bSsiSimpleGroups)
			while (strstrnull(szGroup, "\\")) *strstrnull(szGroup, "\\") = '_'; // remove invalid char

		if (getServListGroupLinkID(szGroup) == wGroupId)
		{ // this grouppath is known and is for this group, set user group
			return szGroup;
		}
		else if (m_bSsiSimpleGroups)
		{ // with simple groups it is mapped 1:1, give real serv-list group name
			setServListGroupLinkID(szGroup, wGroupId);
			return szGroup;
		}
		else
		{ // advanced groups, determine group level
			int nGroupLevel = getServListGroupLevel(wGroupId);

			if (nGroupLevel > 0)
			{ // it is probably a sub-group locate parent group
				WORD wParentGroupId = wGroupId;
				int nParentGroupLevel;

				do
				{ // we look for parent group at the correct level
					wParentGroupId--;
					nParentGroupLevel = getServListGroupLevel(wParentGroupId);
				} while ((nParentGroupLevel >= nGroupLevel) && (nParentGroupLevel != -1));

				if (nParentGroupLevel == -1)
				{ // that was not a sub-group, it was just a group starting with >
					setServListGroupLinkID(szGroup, wGroupId);
					return szGroup;
				}

				{ // recursively determine parent group clist path
					char *szParentGroup = getServListGroupCListPath(wParentGroupId);

					/// FIXME: properly handle ~N suffixes
					szParentGroup = (char*)SAFE_REALLOC(szParentGroup, strlennull(szGroup) + strlennull(szParentGroup) + 2);
					strcat(szParentGroup, "\\");
					strcat(szParentGroup, (char*)szGroup + nGroupLevel);
					/*          if (strstrnull(szGroup, "~"))
					{ // check if the ~ was not added to obtain unique servlist item name
					char *szUniqueMark = strrchr(szParentGroup, '~');

					*szUniqueMark = '\0';
					// not the same group without ~, return it
					if (getServListGroupLinkID(szParentGroup) != wGroupId)
					*szUniqueMark = '~';
					} */ /// FIXME: this is necessary, but needs group loading changes
					SAFE_FREE((void**)&szGroup);
					szGroup = szParentGroup;


					if (getServListGroupLinkID(szGroup) == wGroupId)
					{ // known path, give
						return szGroup;
					}
					else
					{ // unknown path, setup a link
						setServListGroupLinkID(szGroup, wGroupId);
						return szGroup;
					}
				}
			}
			else
			{ // normal group, setup a link
				setServListGroupLinkID(szGroup, wGroupId);
				return szGroup;
			}
		}
	}
	return NULL;
}


static int SrvGroupNamesEnumProc(const char *szSetting, LPARAM lParam)
{ // check server-group cache item
	const char **params = (const char**)lParam;
	CIcqProto *ppro = (CIcqProto*)params[0];
	char *szGroupName = ppro->getSettingStringUtf(NULL, params[3], szSetting, NULL);

	if (!strcmpnull(szGroupName, params[2]))
		params[1] = szSetting; // do not need the real value, just arbitrary non-NULL

	SAFE_FREE(&szGroupName);
	return 0;
}

char* CIcqProto::getServListUniqueGroupName(const char *szGroupName, int bAlloced)
{ // enum ICQSrvGroups and create unique name if neccessary
	DBCONTACTENUMSETTINGS dbces;
	char szModule[MAX_PATH];
	char *pars[4];
	int uniqueID = 1;
	char *szGroupNameBase = (char*)szGroupName;
	char *szNewGroupName = NULL;

	if (!bAlloced)
		szGroupNameBase = null_strdup(szGroupName);
	null_strcut(szGroupNameBase, m_wServerListRecordNameMaxLength);

	mir_snprintf(szModule, SIZEOF(szModule), "%sSrvGroups", m_szModuleName);

	do {
		pars[0] = (char*)this;
		pars[1] = NULL;
		pars[2] = szNewGroupName ? szNewGroupName : szGroupNameBase;
		pars[3] = szModule;

		dbces.pfnEnumProc = &SrvGroupNamesEnumProc;
		dbces.szModule = szModule;
		dbces.lParam = (LPARAM)pars;
		CallService(MS_DB_CONTACT_ENUMSETTINGS, 0, (LPARAM)&dbces);

		if (pars[1])
		{ // the groupname already exists, create another
			SAFE_FREE((void**)&szNewGroupName);

			char szUnique[10];
			_itoa(uniqueID++, szUnique, 10);
			null_strcut(szGroupNameBase, m_wServerListRecordNameMaxLength - strlennull(szUnique) - 1);
			szNewGroupName = (char*)SAFE_MALLOC(strlennull(szUnique) + strlennull(szGroupNameBase) + 2);
			if (szNewGroupName)
			{
				strcpy(szNewGroupName, szGroupNameBase);
				strcat(szNewGroupName, "~");
				strcat(szNewGroupName, szUnique);
			}
		}
	} while (pars[1] && szNewGroupName);

	if (szNewGroupName)
	{
		SAFE_FREE(&szGroupNameBase);
		return szNewGroupName;
	}
	if (szGroupName != szGroupNameBase)
	{
		SAFE_FREE(&szGroupNameBase);
		return (char*)szGroupName;
	}
	else
		return szGroupNameBase;
}


// this is the second part of recursive event-driven procedure
int CIcqProto::servlistCreateGroup_gotParentGroup(const char *szGroup, WORD wGroupID, LPARAM param, int nResult)
{
	cookie_servlist_action* clue = (cookie_servlist_action*)param;
	char *szSubGroupName = clue->szGroupName;
	char *szSubGroup;
	int wSubGroupLevel = -1;
	WORD wSubGroupID;

	SAFE_FREE((void**)&clue);

	if (nResult == PENDING_RESULT_PURGE)
	{ // only cleanup
		return CALLBACK_RESULT_CONTINUE;
	}

	szSubGroup = (char*)SAFE_MALLOC(strlennull(szGroup) + strlennull(szSubGroupName) + 2);
	if (szSubGroup)
	{
		strcpy(szSubGroup, szGroup);
		strcat(szSubGroup, "\\");
		strcat(szSubGroup, szSubGroupName);
	}

	if (nResult == PENDING_RESULT_SUCCESS) // if we got an id count level
		wSubGroupLevel = getServListGroupLevel(wGroupID);

	if (wSubGroupLevel == -1)
	{ // something went wrong, give the id and go away
		servlistPendingRemoveGroup(szSubGroup, wGroupID, PENDING_RESULT_FAILED);

		SAFE_FREE((void**)&szSubGroupName);
		SAFE_FREE((void**)&szSubGroup);
		return CALLBACK_RESULT_CONTINUE;
	}
	wSubGroupLevel++; // we are a sub-group
	wSubGroupID = wGroupID + 1;

	// check if on that id is not group of the same or greater level, if yes, try next
	while (CheckServerID(wSubGroupID, 0) && (getServListGroupLevel(wSubGroupID) >= wSubGroupLevel))
	{
		wSubGroupID++;
	}

	if (!CheckServerID(wSubGroupID, 0))
	{ // the next id is free, so create our group with that id
		cookie_servlist_action *ack;
		DWORD dwCookie;
		char *szSubGroupItem = (char*)SAFE_MALLOC(strlennull(szSubGroupName) + wSubGroupLevel + 1);

		if (szSubGroupItem)
		{
			int i;

			for (i=0; i < wSubGroupLevel; i++)
				szSubGroupItem[i] = '>';

			strcpy(szSubGroupItem + wSubGroupLevel, szSubGroupName);
			szSubGroupItem[strlennull(szSubGroupName) + wSubGroupLevel] = '\0';
			SAFE_FREE((void**)&szSubGroupName);
			// check and create unique group name (Miranda does allow more subgroups with the same name!)
			szSubGroupItem = getServListUniqueGroupName(szSubGroupItem, TRUE);

			if (ack = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action)))
			{ // we have cookie good, go on
#ifdef _DEBUG
				debugLogA("Server-List: Creating sub-group \"%s\", parent group \"%s\".", szSubGroupItem, szGroup);
#endif
				ReserveServerID(wSubGroupID, SSIT_GROUP, 0);

				ack->wGroupId = wSubGroupID;
				ack->szGroupName = szSubGroupItem; // we need that name
				ack->szGroup = szSubGroup;
				ack->dwAction = SSA_GROUP_ADD;
				dwCookie = AllocateCookie(CKT_SERVERLIST, ICQ_LISTS_ADDTOLIST, 0, ack);

				icq_sendServerGroup(dwCookie, ICQ_LISTS_ADDTOLIST, ack->wGroupId, szSubGroupItem, NULL, 0, SSOF_BEGIN_OPERATION);
				return CALLBACK_RESULT_CONTINUE;
			}
			SAFE_FREE((void**)&szSubGroupItem);
		}
	}
	// we failed to create sub-group give parent groupid
	icq_LogMessage(LOG_ERROR, LPGEN("Failed to create the correct sub-group, the using closest parent group."));

	servlistPendingRemoveGroup(szSubGroup, wGroupID, PENDING_RESULT_FAILED);

	SAFE_FREE((void**)&szSubGroupName);
	SAFE_FREE((void**)&szSubGroup);
	return CALLBACK_RESULT_CONTINUE;
}


int CIcqProto::servlistCreateGroup_Ready(const char *szGroup, WORD groupID, LPARAM param, int nResult)
{
	WORD wGroupID = 0;

	if (nResult == PENDING_RESULT_PURGE)
		return CALLBACK_RESULT_CONTINUE;

	if (wGroupID = getServListGroupLinkID(szGroup))
	{ // the path is known, continue the process
		servlistPendingRemoveGroup(szGroup, wGroupID, PENDING_RESULT_SUCCESS);
		return CALLBACK_RESULT_CONTINUE;
	}

	if (!strstrnull(szGroup, "\\") || m_bSsiSimpleGroups)
	{ // a root group can be simply created without problems; simple groups are mapped directly
		cookie_servlist_action* ack;
		DWORD dwCookie;

		if (ack = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action)))
		{ // we have cookie good, go on
#ifdef _DEBUG
			debugLogA("Server-List: Creating root group \"%s\".", szGroup);
#endif
			ack->wGroupId = GenerateServerID(SSIT_GROUP, 0);
			ack->szGroup = null_strdup(szGroup); // we need that name
			// check if the groupname is unique - just to be sure, Miranda should handle that!
			ack->szGroupName = getServListUniqueGroupName(ack->szGroup, FALSE);
			ack->dwAction = SSA_GROUP_ADD;
			dwCookie = AllocateCookie(CKT_SERVERLIST, ICQ_LISTS_ADDTOLIST, 0, ack);

			icq_sendServerGroup(dwCookie, ICQ_LISTS_ADDTOLIST, ack->wGroupId, ack->szGroup, NULL, 0, SSOF_BEGIN_OPERATION);

			return CALLBACK_RESULT_POSTPONE;
		}
	}
	else
	{ // this is a sub-group
		char* szSub = null_strdup(szGroup); // create subgroup, recursive, event-driven, possibly relocate
		cookie_servlist_action* ack;
		char *szLast;

		if (strstrnull(szSub, "\\"))
		{ // determine parent group
			szLast = strrchr(szSub, '\\') + 1;

			szLast[-1] = '\0'; 
		}
		// make parent group id
		ack = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action));
		if (ack)
		{
			ack->szGroupName = null_strdup(szLast); // groupname
			servlistCreateGroup(szSub, (LPARAM)ack, &CIcqProto::servlistCreateGroup_gotParentGroup);
			SAFE_FREE((void**)&szSub);

			return CALLBACK_RESULT_POSTPONE;
		}

		SAFE_FREE((void**)&szSub); 
	}
	servlistPendingRemoveGroup(szGroup, groupID, PENDING_RESULT_FAILED);

	return CALLBACK_RESULT_CONTINUE;
}


// create group with this path, a bit complex task
// this supposes that all server groups are known
void CIcqProto::servlistCreateGroup(const char *szGroupPath, LPARAM param, PENDING_GROUP_CALLBACK callback)
{
	char *szGroup = (char*)szGroupPath;

	if (!strlennull(szGroup)) szGroup = DEFAULT_SS_GROUP;

	servlistPendingAddGroup(szGroup, 0, 0, &CIcqProto::servlistCreateGroup_Ready, TRUE, param, callback);
}


/*****************************************
*
*    --- Server-List Operations ---
*
*/

int CIcqProto::servlistAddContact_gotGroup(const char *szGroup, WORD wGroupID, LPARAM lParam, int nResult)
{
	cookie_servlist_action* ack = (cookie_servlist_action*)lParam;

	if (ack) SAFE_FREE(&ack->szGroup);

	if (nResult == PENDING_RESULT_PURGE)
	{ // only cleanup
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	if (!ack || !wGroupID) // something went wrong
	{
		if (ack) servlistPendingRemoveContact(ack->hContact, 0, wGroupID, PENDING_RESULT_FAILED);
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	WORD wItemID = getWord(ack->hContact, DBSETTING_SERVLIST_ID, 0);

	if (wItemID) /// TODO: redundant ???
	{ // Only add the contact if it doesnt already have an ID
		servlistPendingRemoveContact(ack->hContact, wItemID, wGroupID, PENDING_RESULT_SUCCESS);
		debugLogA("Failed to add contact to server side list (%s)", "already there");
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	wItemID = GenerateServerID(SSIT_ITEM, 0);

	ack->dwAction = SSA_CONTACT_ADD;
	ack->wGroupId = wGroupID;
	ack->wContactId = wItemID;

	DWORD dwCookie = AllocateCookie(CKT_SERVERLIST, ICQ_LISTS_ADDTOLIST, ack->hContact, ack);

	icq_sendServerContact(ack->hContact, dwCookie, ICQ_LISTS_ADDTOLIST, wGroupID, wItemID, SSOP_ITEM_ACTION | SSOF_CONTACT | SSOF_BEGIN_OPERATION, 400, NULL);

	return CALLBACK_RESULT_CONTINUE;
}


// Need to be called when Pending Contact is active
int CIcqProto::servlistAddContact_Ready(MCONTACT hContact, WORD wContactID, WORD wGroupID, LPARAM lParam, int nResult)
{
	cookie_servlist_action* ack = (cookie_servlist_action*)lParam;

	if (nResult == PENDING_RESULT_PURGE)
	{ // removing obsolete items, just free the memory
		SAFE_FREE((void**)&ack->szGroup);
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	WORD wItemID = getWord(ack->hContact, DBSETTING_SERVLIST_ID, 0);

	if (wItemID)
	{ // Only add the contact if it doesn't already have an ID
		servlistPendingRemoveContact(ack->hContact, wItemID, getWord(hContact, DBSETTING_SERVLIST_GROUP, 0), PENDING_RESULT_SUCCESS);
		debugLogA("Failed to add contact to server side list (%s)", "already there");
		SAFE_FREE((void**)&ack->szGroup);
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	// obtain a correct groupid first
	servlistCreateGroup(ack->szGroup, lParam, &CIcqProto::servlistAddContact_gotGroup);

	return CALLBACK_RESULT_POSTPONE;
}


// Called when contact should be added to server list, if group does not exist, create one
void CIcqProto::servlistAddContact(MCONTACT hContact, const char *pszGroup)
{
	DWORD dwUin;
	uid_str szUid;
	cookie_servlist_action* ack;

	// Get UID
	if (getContactUid(hContact, &dwUin, &szUid))
	{ // Could not do anything without uid
		debugLogA("Failed to add contact to server side list (%s)", "no UID");
		return;
	}

	if (!(ack = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action))))
	{ // Could not do anything without cookie
		debugLogA("Failed to add contact to server side list (%s)", "malloc failed");
		return;
	}
	else
	{
		ack->hContact = hContact;
		ack->szGroup = null_strdup(pszGroup);
		// call thru pending operations - makes sure the contact is ready to be added
		servlistPendingAddContact(hContact, 0, 0, (LPARAM)ack, &CIcqProto::servlistAddContact_Ready, TRUE);
		return;
	}
}


int CIcqProto::servlistRemoveContact_Ready(MCONTACT hContact, WORD contactID, WORD groupID, LPARAM lParam, int nResult)
{
	WORD wGroupID;
	WORD wItemID;
	cookie_servlist_action* ack = (cookie_servlist_action*)lParam;
	DWORD dwCookie;

	if (nResult == PENDING_RESULT_PURGE)
	{
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	// Get the contact's group ID
	if (!(wGroupID = getWord(hContact, DBSETTING_SERVLIST_GROUP, 0)))
	{ // Could not find a usable group ID
		servlistPendingRemoveContact(hContact, contactID, groupID, PENDING_RESULT_FAILED);

		debugLogA("Failed to remove contact from server side list (%s)", "no group ID");
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	// Get the contact's item ID
	if (!(wItemID = getWord(hContact, DBSETTING_SERVLIST_ID, 0)))
	{ // Could not find usable item ID
		servlistPendingRemoveContact(hContact, contactID, wGroupID, PENDING_RESULT_FAILED);

		debugLogA("Failed to remove contact from server side list (%s)", "no item ID");
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	ack->dwAction = SSA_CONTACT_REMOVE;
	ack->hContact = hContact;
	ack->wGroupId = wGroupID;
	ack->wContactId = wItemID;

	dwCookie = AllocateCookie(CKT_SERVERLIST, ICQ_LISTS_REMOVEFROMLIST, hContact, ack);

	icq_sendServerContact(hContact, dwCookie, ICQ_LISTS_REMOVEFROMLIST, wGroupID, wItemID, SSOP_ITEM_ACTION | SSOF_CONTACT | SSOF_BEGIN_OPERATION, 400, NULL);

	return CALLBACK_RESULT_POSTPONE;
}


// Called when contact should be removed from server list, remove group if it remain empty
void CIcqProto::servlistRemoveContact(MCONTACT hContact)
{
	DWORD dwUin;
	uid_str szUid;
	cookie_servlist_action* ack;

	// Get UID
	if (getContactUid(hContact, &dwUin, &szUid))
	{
		// Could not do anything without uid
		debugLogA("Failed to remove contact from server side list (%s)", "no UID");
		return;
	}

	if (!(ack = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action))))
	{ // Could not do anything without cookie
		debugLogA("Failed to remove contact from server side list (%s)", "malloc failed");
		return;
	}
	else
	{
		ack->hContact = hContact;
		// call thru pending operations - makes sure the contact is ready to be removed
		servlistPendingAddContact(hContact, 0, 0, (LPARAM)ack, &CIcqProto::servlistRemoveContact_Ready, TRUE);
		return;
	}
}


int CIcqProto::servlistMoveContact_gotTargetGroup(const char *szGroup, WORD wNewGroupID, LPARAM lParam, int nResult)
{
	cookie_servlist_action *ack = (cookie_servlist_action*)lParam;

	if (ack) SAFE_FREE(&ack->szGroup);

	if (nResult == PENDING_RESULT_PURGE)
	{ // removing obsolete items, just free the memory
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	if (!ack || !wNewGroupID || !ack->hContact) // something went wrong
	{
		if (ack) servlistPendingRemoveContact(ack->hContact, 0, 0, PENDING_RESULT_FAILED);
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	WORD wItemID = getWord(ack->hContact, DBSETTING_SERVLIST_ID, 0);
	WORD wGroupID = getWord(ack->hContact, DBSETTING_SERVLIST_GROUP, 0);

	if (!wItemID) 
	{ // We have no ID, so try to simply add the contact to serv-list 
		debugLogA("Unable to move contact (no ItemID) -> trying to add");
		// we know the GroupID, so directly call add
		return servlistAddContact_gotGroup(szGroup, wNewGroupID, lParam, nResult);
	}

	if (wGroupID == wNewGroupID)
	{ // Only move the contact if it had different GroupID
		servlistPendingRemoveContact(ack->hContact, wItemID, wNewGroupID, PENDING_RESULT_SUCCESS);
		debugLogA("Contact not moved to group on server side list (same Group)");
		return CALLBACK_RESULT_CONTINUE;
	}

	ack->szGroupName = NULL;
	ack->dwAction = SSA_CONTACT_SET_GROUP;
	ack->wGroupId = wGroupID;
	ack->wContactId = wItemID;
	ack->wNewContactId = GenerateServerID(SSIT_ITEM, 0); // icq5 recreates also this, imitate
	ack->wNewGroupId = wNewGroupID;
	ack->lParam = 0; // we use this as a sign

	DWORD dwCookie = AllocateCookie(CKT_SERVERLIST, ICQ_LISTS_REMOVEFROMLIST, ack->hContact, ack);
	DWORD dwCookie2 = AllocateCookie(CKT_SERVERLIST, ICQ_LISTS_ADDTOLIST, ack->hContact, ack);

	{ // imitate icq5, previously here was different order, but AOL changed and it ceased to work
		void *doubleObject = NULL;

		icq_sendServerContact(ack->hContact, dwCookie2, ICQ_LISTS_ADDTOLIST, wNewGroupID, ack->wNewContactId, SSO_CONTACT_SETGROUP | SSOF_BEGIN_OPERATION, 500, &doubleObject);
		icq_sendServerContact(ack->hContact, dwCookie, ICQ_LISTS_REMOVEFROMLIST, wGroupID, wItemID, SSO_CONTACT_SETGROUP | SSOF_BEGIN_OPERATION, 500, &doubleObject);
	}
	return CALLBACK_RESULT_CONTINUE;
}


int CIcqProto::servlistMoveContact_Ready(MCONTACT hContact, WORD contactID, WORD groupID, LPARAM lParam, int nResult)
{
	cookie_servlist_action *ack = (cookie_servlist_action*)lParam;

	if (nResult == PENDING_RESULT_PURGE)
	{ // removing obsolete items, just free the memory
		SAFE_FREE(&ack->szGroup);
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	WORD wItemID = getWord(ack->hContact, DBSETTING_SERVLIST_ID, 0);
	WORD wGroupID = getWord(ack->hContact, DBSETTING_SERVLIST_GROUP, 0);

	if (!wGroupID && wItemID)
	{ // Only move the contact if it had an GroupID
		servlistPendingRemoveContact(ack->hContact, contactID, groupID, PENDING_RESULT_FAILED);

		debugLogA("Failed to move contact to group on server side list (%s)", "no Group");
		SAFE_FREE(&ack->szGroup);
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	// obtain a correct target groupid first
	servlistCreateGroup(ack->szGroup, lParam, &CIcqProto::servlistMoveContact_gotTargetGroup);

	return CALLBACK_RESULT_POSTPONE;
}


// Called when contact should be moved from one group to another, create new, remove empty
void CIcqProto::servlistMoveContact(MCONTACT hContact, const char *pszNewGroup)
{
	DWORD dwUin;
	uid_str szUid;

	if (!hContact) return; // we do not move us, caused our uin was wrongly added to list

	// Get UID
	if (getContactUid(hContact, &dwUin, &szUid))
	{ // Could not do anything without uin
		debugLogA("Failed to move contact to group on server side list (%s)", "no UID");
		return;
	}

	if ((pszNewGroup != NULL) && (pszNewGroup[0]!='\0') && !getCListGroupExists(pszNewGroup))
	{ // the contact moved to non existing group, do not do anything: MetaContact hack
		debugLogA("Contact not moved - probably hiding by MetaContacts.");
		return;
	}

	if (!getWord(hContact, DBSETTING_SERVLIST_ID, 0)) /// FIXME:::: this should be in _ready
	{ // the contact is not stored on the server, check if we should try to add
		if (!getByte("ServerAddRemove", DEFAULT_SS_ADDSERVER) ||
			db_get_b(hContact, "CList", "Hidden", 0))
			return;
	}
	cookie_servlist_action *ack = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action));

	if (!ack)
	{ // Could not do anything without cookie
		debugLogA("Failed to add contact to server side list (%s)", "malloc failed");
		return;
	}
	else
	{
		ack->hContact = hContact;
		ack->szGroup = null_strdup(pszNewGroup);
		// call thru pending operations - makes sure the contact is ready to be moved
		servlistPendingAddContact(hContact, 0, 0, (LPARAM)ack, &CIcqProto::servlistMoveContact_Ready, TRUE);
		return;
	}
}


int CIcqProto::servlistUpdateContact_Ready(MCONTACT hContact, WORD contactID, WORD groupID, LPARAM lParam, int nResult)
{
	cookie_servlist_action *ack = (cookie_servlist_action*)lParam;

	if (nResult == PENDING_RESULT_PURGE)
	{ // removing obsolete items, just free the memory
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}
	WORD wItemID;
	WORD wGroupID;

	// Get the contact's group ID
	if (!(wGroupID = getWord(hContact, DBSETTING_SERVLIST_GROUP, 0)))
	{
		servlistPendingRemoveContact(hContact, contactID, groupID, PENDING_RESULT_FAILED);
		// Could not find a usable group ID
		debugLogA("Failed to update contact's details on server side list (%s)", "no group ID");
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	// Get the contact's item ID
	if (!(wItemID = getWord(hContact, DBSETTING_SERVLIST_ID, 0)))
	{
		servlistPendingRemoveContact(hContact, contactID, wGroupID, PENDING_RESULT_FAILED);
		// Could not find usable item ID
		debugLogA("Failed to update contact's details on server side list (%s)", "no item ID");
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	ack->dwAction = SSA_CONTACT_UPDATE;
	ack->wContactId = wItemID;
	ack->wGroupId = wGroupID;
	ack->hContact = hContact;

	DWORD dwCookie = AllocateCookie(CKT_SERVERLIST, ICQ_LISTS_UPDATEGROUP, hContact, ack);

	// There is no need to send ICQ_LISTS_CLI_MODIFYSTART or
	// ICQ_LISTS_CLI_MODIFYEND when just changing nick name
	icq_sendServerContact(hContact, dwCookie, ICQ_LISTS_UPDATEGROUP, wGroupID, wItemID, SSOP_ITEM_ACTION | SSOF_CONTACT, 400, NULL);

	return CALLBACK_RESULT_POSTPONE;
}


// Is called when a contact' details has been changed locally to update
// the server side details.
void CIcqProto::servlistUpdateContact(MCONTACT hContact)
{
	DWORD dwUin;
	uid_str szUid;

	// Get UID
	if (getContactUid(hContact, &dwUin, &szUid))
	{
		// Could not set nickname on server without uid
		debugLogA("Failed to update contact's details on server side list (%s)", "no UID");
		return;
	}
	cookie_servlist_action *ack = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action));

	if (!ack)
	{
		// Could not allocate cookie - use old fake
		debugLogA("Failed to update contact's details on server side list (%s)", "malloc failed");
		return;
	}
	else
	{
		ack->hContact = hContact;
		// call thru pending operations - makes sure the contact is ready to be updated
		servlistPendingAddContact(hContact, 0, 0, (LPARAM)ack, &CIcqProto::servlistUpdateContact_Ready, TRUE);
		return;
	}
}


int CIcqProto::servlistRenameGroup_Ready(const char *szGroup, WORD wGroupID, LPARAM lParam, int nResult)
{
	cookie_servlist_action *ack = (cookie_servlist_action*)lParam;

	if (nResult == PENDING_RESULT_PURGE)
	{ // only cleanup
		if (ack) SAFE_FREE(&ack->szGroupName);
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}

	if (!ack || !wGroupID) // something went wrong
	{
		servlistPendingRemoveGroup(szGroup, wGroupID, PENDING_RESULT_FAILED);

		if (ack) SAFE_FREE(&ack->szGroupName);
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}
	void *groupData;
	int groupSize;

	if (groupData = collectBuddyGroup(wGroupID, &groupSize))
	{
		ack->dwAction = SSA_GROUP_RENAME;
		ack->wGroupId = wGroupID;
		ack->szGroup = null_strdup(szGroup); // we need this name
		// check if the new name is unique, create unique groupname if necessary
		ack->szGroupName = getServListUniqueGroupName(ack->szGroupName, TRUE);

		DWORD dwCookie = AllocateCookie(CKT_SERVERLIST, ICQ_LISTS_UPDATEGROUP, 0, ack);

		icq_sendServerGroup(dwCookie, ICQ_LISTS_UPDATEGROUP, wGroupID, ack->szGroupName, groupData, groupSize, 0);
		SAFE_FREE(&groupData);
	}
	return CALLBACK_RESULT_POSTPONE;
}


void CIcqProto::servlistRenameGroup(char *szGroup, WORD wGroupId, char *szNewGroup)
{
	char *szNewGroupName;
	int nGroupLevel = getServListGroupLevel(wGroupId);

	if (nGroupLevel == -1) return; // we failed to prepare group

	if (!m_bSsiSimpleGroups)
	{
		char *szGroupName = szGroup;
		int i = nGroupLevel;
		while (i)
		{ // find correct part of grouppath
			szGroupName = strstrnull(szGroupName, "\\");
			if (!szGroupName) return; // failed to get correct part of the grouppath
			szGroupName++;
			i--;
		}
		szNewGroupName = szNewGroup;
		i = nGroupLevel;
		while (i)
		{ // find correct part of new grouppath
			szNewGroupName = strstrnull(szNewGroupName, "\\");
			if (!szNewGroupName) return; // failed to get correct part of the new grouppath
			szNewGroupName++;
			i--;
		}
		// truncate possible sub-groups
		char *szLast = strstrnull(szGroupName, "\\");
		if (szLast)
			szLast[0] = '\0';
		szLast = strstrnull(szNewGroupName, "\\");
		if (szLast)
			szLast[0] = '\0';

		// this group was not changed, nothing to rename
		if (!strcmpnull(szGroupName, szNewGroupName)) return;

		szGroupName = szNewGroupName;
		szNewGroupName = (char*)SAFE_MALLOC(strlennull(szGroupName) + 1 + nGroupLevel);
		if (!szNewGroupName) return; // Failure

		for (i = 0; i < nGroupLevel; i++)
		{ // create level prefix
			szNewGroupName[i] = '>';
		}
		strcat(szNewGroupName, szGroupName);
	}
	else // simple groups do not require any conversion
		szNewGroupName = null_strdup(szNewGroup);

	cookie_servlist_action* ack = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action));
	if (!ack)
	{ // cookie failed
		debugLogA("Error: Failed to allocate cookie");

		SAFE_FREE(&szNewGroupName);
		return;
	}
	// store new group name for future use
	ack->szGroupName = szNewGroupName;
	// call thru pending operations - makes sure the group is ready for rename
	servlistPendingAddGroup(szGroup, wGroupId, (LPARAM)ack, &CIcqProto::servlistRenameGroup_Ready, TRUE);
}


int CIcqProto::servlistRemoveGroup_Ready(const char *szGroup, WORD groupID, LPARAM lParam, int nResult)
{
	cookie_servlist_action *ack = (cookie_servlist_action*)lParam;

	if (nResult == PENDING_RESULT_PURGE)
	{ // only cleanup
		SAFE_FREE((void**)&ack);
		return CALLBACK_RESULT_CONTINUE;
	}
	WORD wGroupID = getServListGroupLinkID(szGroup);
	char *szGroupName;

	if (wGroupID && (szGroupName = getServListGroupName(wGroupID)))
	{ // the group is valid, check if it is empty
		void *groupData = collectBuddyGroup(wGroupID, NULL);

		if (groupData)
		{ // the group is not empty, cannot delete
			SAFE_FREE(&groupData);
			SAFE_FREE(&szGroupName);
			// end operation
			servlistPendingRemoveGroup(szGroup, wGroupID, PENDING_RESULT_SUCCESS);
			// cleanup
			SAFE_FREE((void**)&ack);
			return CALLBACK_RESULT_CONTINUE;
		}

		if (!CheckServerID((WORD)(wGroupID+1), 0) || getServListGroupLevel((WORD)(wGroupID+1)) == 0)
		{ // is next id an sub-group, if yes, we cannot delete this group
			ack->dwAction = SSA_GROUP_REMOVE;
			ack->wContactId = 0;
			ack->wGroupId = wGroupID;
			ack->hContact = NULL;
			ack->szGroup = null_strdup(szGroup); // we need that name
			ack->szGroupName = szGroupName;
			DWORD dwCookie = AllocateCookie(CKT_SERVERLIST, ICQ_LISTS_REMOVEFROMLIST, 0, ack);

			icq_sendServerGroup(dwCookie, ICQ_LISTS_REMOVEFROMLIST, ack->wGroupId, ack->szGroupName, NULL, 0, 0);
		}
		return CALLBACK_RESULT_POSTPONE;
	}
	// end operation
	servlistPendingRemoveGroup(szGroup, groupID, PENDING_RESULT_SUCCESS);
	// cleanup
	SAFE_FREE((void**)&ack);
	return CALLBACK_RESULT_CONTINUE;
}


void CIcqProto::servlistRemoveGroup(const char *szGroup, WORD wGroupId)
{
	if (!szGroup) return;

	cookie_servlist_action *ack = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action));

	if (!ack)
	{ // cookie failed
		debugLogA("Error: Failed to allocate cookie");
		return;
	}

	// call thru pending operations - makes sure the group is ready for removal
	servlistPendingAddGroup(szGroup, wGroupId, (LPARAM)ack, &CIcqProto::servlistRemoveGroup_Ready, TRUE);
}


/*void CIcqProto::servlistMoveGroup(const char *szGroup, WORD wNewGroupId)
{
// relocate the group
}*/


void CIcqProto::resetServContactAuthState(MCONTACT hContact, DWORD dwUin)
{
	WORD wContactId = getWord(hContact, DBSETTING_SERVLIST_ID, 0);
	WORD wGroupId = getWord(hContact, DBSETTING_SERVLIST_GROUP, 0);

	if (wContactId && wGroupId)
	{
		cookie_servlist_action *ack = (cookie_servlist_action*)SAFE_MALLOC(sizeof(cookie_servlist_action));

		if (ack)
		{ // we have cookie good, go on
			ack->hContact = hContact;
			ack->wContactId = wContactId;
			ack->wGroupId = wGroupId;
			ack->dwAction = SSA_CONTACT_FIX_AUTH;

			DWORD dwCookie = AllocateCookie(CKT_SERVERLIST, 0, hContact, ack);

			{
				void *doubleObject = NULL;

				icq_sendServerContact(hContact, dwCookie, ICQ_LISTS_REMOVEFROMLIST, wGroupId, wContactId, SSO_CONTACT_FIXAUTH | SSOF_BEGIN_OPERATION | SSOF_END_OPERATION, 200, &doubleObject);
				delSetting(hContact, DBSETTING_METAINFO_TOKEN);
				delSetting(hContact, DBSETTING_METAINFO_TIME);
				delSetting(hContact, DBSETTING_SERVLIST_DATA);
				icq_sendServerContact(hContact, dwCookie, ICQ_LISTS_ADDTOLIST, wGroupId, wContactId, SSO_CONTACT_FIXAUTH | SSOF_BEGIN_OPERATION | SSOF_END_OPERATION, 200, &doubleObject);
			}
		}
		else
			debugLogA("Error: Failed to allocate cookie");
	}
}

/*****************************************
*
*   --- Miranda Contactlist Hooks ---
*
*/

int CIcqProto::ServListDbSettingChanged(WPARAM hContact, LPARAM lParam)
{
	DBCONTACTWRITESETTING* cws = (DBCONTACTWRITESETTING*)lParam;

	// TODO: Queue changes that occur while offline
	if (!icqOnline() || !m_bSsiEnabled || bIsSyncingCL)
		return 0;

#ifdef _DEBUG
	if (cws->value.type == DBVT_DELETED)
		debugLogA("DB-Events: Module \"%s\", setting \"%s\" deleted.", cws->szModule, cws->szSetting);
	else
		debugLogA("DB-Events: Module \"%s\", setting \"%s\" changed, data type %x.", cws->szModule, cws->szSetting, cws->value.type);
#endif

	if (!strcmpnull(cws->szModule, "CList"))
	{
		// Has contact been renamed?
		if (!strcmpnull(cws->szSetting, "MyHandle") && getByte("StoreServerDetails", DEFAULT_SS_STORE))
			servlistUpdateContact(hContact); // Update contact's details in server-list

		// Has contact been moved to another group?
		if (!strcmpnull(cws->szSetting, "Group") && getByte("StoreServerDetails", DEFAULT_SS_STORE)) {
			char* szNewGroup = getContactCListGroup(hContact); // Read group from DB
			SAFE_FREE(&szNewGroup);
		}
	}
	else if (!strcmpnull(cws->szModule, "UserInfo")) {
		// Update contact's details in server-list
		if (!strcmpnull(cws->szSetting, "MyNotes") && getByte("StoreServerDetails", DEFAULT_SS_STORE))
			servlistUpdateContact(hContact);
	}

	return 0;
}


int CIcqProto::ServListDbContactDeleted(WPARAM hContact, LPARAM lParam)
{
#ifdef _DEBUG
	debugLogA("DB-Events: Contact %x deleted.", hContact);
#endif

	DeleteFromContactsCache(hContact);

	if ( !icqOnline() && m_bSsiEnabled)
		// contact was deleted only locally - retrieve full list on next connect
		setWord(hContact, "SrvRecordCount", 0);

	if ( !icqOnline() || !m_bSsiEnabled)
		return 0;

	// we need all server contacts on local buddy list
	DWORD dwUIN;
	uid_str szUID;
	if (getContactUid(hContact, &dwUIN, &szUID))
		return 0;

	WORD wContactID = getWord(hContact, DBSETTING_SERVLIST_ID, 0);
	WORD wGroupID = getWord(hContact, DBSETTING_SERVLIST_GROUP, 0);
	WORD wVisibleID = getWord(hContact, DBSETTING_SERVLIST_PERMIT, 0);
	WORD wInvisibleID = getWord(hContact, DBSETTING_SERVLIST_DENY, 0);
	WORD wIgnoreID = getWord(hContact, DBSETTING_SERVLIST_IGNORE, 0);

	// Remove from queue for user details request
	icq_DequeueUser(dwUIN);

	// Close all opened peer connections
	CloseContactDirectConns(hContact);

	if ((wGroupID && wContactID) || wVisibleID || wInvisibleID || wIgnoreID) {
		if (wContactID) // delete contact from server
			servlistRemoveContact(hContact);

		if (wVisibleID) // detete permit record
			icq_removeServerPrivacyItem(hContact, dwUIN, szUID, wVisibleID, SSI_ITEM_PERMIT);

		if (wInvisibleID) // delete deny record
			icq_removeServerPrivacyItem(hContact, dwUIN, szUID, wInvisibleID, SSI_ITEM_DENY);

		if (wIgnoreID) // delete ignore record
			icq_removeServerPrivacyItem(hContact, dwUIN, szUID, wIgnoreID, SSI_ITEM_IGNORE);
	}

	return 0;
}


int CIcqProto::ServListCListGroupChange(WPARAM hContact, LPARAM lParam)
{
	CLISTGROUPCHANGE *grpchg = (CLISTGROUPCHANGE*)lParam;

	if (!icqOnline() || !m_bSsiEnabled || bIsSyncingCL)
		return 0;

	// only change server-list if it is allowed
	if (!getByte("StoreServerDetails", DEFAULT_SS_STORE))
		return 0;


	if (hContact == NULL)
	{ // change made to group
		if (grpchg->pszNewName == NULL && grpchg->pszOldName != NULL)
		{ // group removed
			char *szOldName = tchar_to_utf8(grpchg->pszOldName);
			WORD wGroupId = getServListGroupLinkID(szOldName);

#ifdef _DEBUG
			debugLogA("CList-Events: Group %x:\"%s\" deleted.", wGroupId, szOldName);
#endif
			if (wGroupId)
			{ // the group is known, remove from server
				servlistPostPacket(NULL, 0, SSO_BEGIN_OPERATION, 100); // start server modifications here
				servlistRemoveGroup(szOldName, wGroupId);
			}
			SAFE_FREE(&szOldName);
		}
		else if (grpchg->pszNewName != NULL && grpchg->pszOldName != NULL)
		{ // group renamed
			char *szNewName = tchar_to_utf8(grpchg->pszNewName);
			char *szOldName = tchar_to_utf8(grpchg->pszOldName);
			WORD wGroupId = getServListGroupLinkID(szOldName);

#ifdef _DEBUG
			debugLogA("CList-Events: Group %x:\"%s\" changed to \"%s\".", wGroupId, szOldName, szNewName);
#endif
			if (wGroupId)
			{ // group is known, rename on server
				servlistRenameGroup(szOldName, wGroupId, szNewName);
			}
			SAFE_FREE(&szOldName);
			SAFE_FREE(&szNewName);
		}
	}
	else
	{ // change to contact
		if (IsICQContact(hContact))
		{ // our contact, fine move on the server as well
			char *szNewName = grpchg->pszNewName ? tchar_to_utf8(grpchg->pszNewName) : NULL;

#ifdef _DEBUG
			debugLogA("CList-Events: Contact %x moved to group \"%s\".", hContact, szNewName);
#endif
			servlistMoveContact(hContact, szNewName);
			SAFE_FREE(&szNewName);
		}
	}
	return 0;
}