summaryrefslogtreecommitdiff
path: root/icqj_s7_sss_mod/icq_servlist.c
blob: e7ba6b10b0795c48e5a4d800e1ee670e7c976b59 (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
// ---------------------------------------------------------------------------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,2003,2004 Martin berg, Sam Kothari, Robert Rainwater
// Copyright  2004,2005,2006,2007 Joe Kucera
// Copyright  2006,2007 [sss], chaos.persei, [sin], Faith Healer, Theif, nullbie
// 
// 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//
// -----------------------------------------------------------------------------
//
// File name      : $Source$
// Revision       : $Revision: 36 $
// Last change on : $Date: 2007-08-05 03:45:10 +0300 (Вс, 05 авг 2007) $
// Last change by : $Author: sss123next $
//
// DESCRIPTION:
//
//  Functions that handles list of used server IDs, sends low-level packets for SSI information
//
// -----------------------------------------------------------------------------

#include "icqoscar.h"



extern BOOL bIsSyncingCL;

static HANDLE hHookSettingChanged = NULL;
static HANDLE hHookContactDeleted = NULL;
static DWORD* pwIDList = NULL;
static int nIDListCount = 0;
static int nIDListSize = 0;



// cookie struct for pending records
typedef struct ssipendingitem_t
{
  HANDLE hContact;
  char* szGroupPath;
  GROUPADDCALLBACK ofCallback;
  servlistcookie* pCookie;
} ssipendingitem;

static CRITICAL_SECTION servlistMutex;
static int nPendingCount = 0;
static int nPendingSize = 0;
static ssipendingitem** pdwPendingList = NULL;
static int nJustAddedCount = 0;
static int nJustAddedSize = 0;
static HANDLE* pdwJustAddedList = NULL;
static WORD* pwGroupRenameList = NULL;
static int nGroupRenameCount = 0;
static int nGroupRenameSize = 0;

static DWORD updateServContact(HANDLE hContact);


// Add running group rename operation
void AddGroupRename(WORD wGroupID)
{
  EnterCriticalSection(&servlistMutex);
  if (nGroupRenameCount >= nGroupRenameSize)
  {
    nGroupRenameSize += 10;
    pwGroupRenameList = (WORD*)SAFE_REALLOC(pwGroupRenameList, nGroupRenameSize * sizeof(WORD));
  }

  pwGroupRenameList[nGroupRenameCount] = wGroupID;
  nGroupRenameCount++;  
  LeaveCriticalSection(&servlistMutex);
}


// Remove running group rename operation
void RemoveGroupRename(WORD wGroupID)
{
  int i, j;

  EnterCriticalSection(&servlistMutex);
  if (pwGroupRenameList)
  {
    for (i = 0; i<nGroupRenameCount; i++)
    {
      if (pwGroupRenameList[i] == wGroupID)
      { // we found it, so remove
        for (j = i+1; j<nGroupRenameCount; j++)
        {
          pwGroupRenameList[j-1] = pwGroupRenameList[j];
        }
        nGroupRenameCount--;
      }
    }
  }
  LeaveCriticalSection(&servlistMutex);
}


// Returns true if dwID is reserved
BOOL IsGroupRenamed(WORD wGroupID)
{
  int i;

  EnterCriticalSection(&servlistMutex);
  if (pwGroupRenameList)
  {
    for (i = 0; i<nGroupRenameCount; i++)
    {
      if (pwGroupRenameList[i] == wGroupID)
      {
        LeaveCriticalSection(&servlistMutex);
        return TRUE;
      }
    }
  }
  LeaveCriticalSection(&servlistMutex);

  return FALSE;
}


void FlushGroupRenames()
{
  EnterCriticalSection(&servlistMutex);
  SAFE_FREE(&pwGroupRenameList);
  nGroupRenameCount = 0;
  nGroupRenameSize = 0;
  LeaveCriticalSection(&servlistMutex);
}


// used for adding new contacts to list - sync with visible items
void AddJustAddedContact(HANDLE hContact)
{
  EnterCriticalSection(&servlistMutex);
  if (nJustAddedCount >= nJustAddedSize)
  {
    nJustAddedSize += 10;
    pdwJustAddedList = (HANDLE*)SAFE_REALLOC(pdwJustAddedList, nJustAddedSize * sizeof(HANDLE));
  }

  pdwJustAddedList[nJustAddedCount] = hContact;
  nJustAddedCount++;  
  LeaveCriticalSection(&servlistMutex);
}


// was the contact added during this serv-list load
BOOL IsContactJustAdded(HANDLE hContact)
{
  int i;

  EnterCriticalSection(&servlistMutex);
  if (pdwJustAddedList)
  {
    for (i = 0; i<nJustAddedCount; i++)
    {
      if (pdwJustAddedList[i] == hContact)
      {
        LeaveCriticalSection(&servlistMutex);
        return TRUE;
      }
    }
  }
  LeaveCriticalSection(&servlistMutex);

  return FALSE;
}


void FlushJustAddedContacts()
{
  EnterCriticalSection(&servlistMutex);
  SAFE_FREE((void**)&pdwJustAddedList);
  nJustAddedSize = 0;
  nJustAddedCount = 0;
  LeaveCriticalSection(&servlistMutex);
}



// Used for event-driven adding of contacts, before it is completed this is used
static BOOL AddPendingOperation(HANDLE hContact, const char* szGroup, servlistcookie* cookie, GROUPADDCALLBACK ofEvent)
{
  BOOL bRes = TRUE;
  ssipendingitem* pItem = NULL;
  int i;

  EnterCriticalSection(&servlistMutex);
  if (pdwPendingList)
  {
    for (i = 0; i<nPendingCount; i++)
    {
      if (pdwPendingList[i]->hContact == hContact)
      { // we need the last item for this contact
        pItem = pdwPendingList[i];
      }
    }
  }

  if (pItem) // we found a pending operation, so link our data
  {
    pItem->ofCallback = ofEvent;
    pItem->pCookie = cookie;
    pItem->szGroupPath = null_strdup(szGroup); // we need to duplicate the string
    bRes = FALSE;

    NetLog_Server("Operation postponed.");
  }
  
  if (nPendingCount >= nPendingSize) // add new
  {
    nPendingSize += 10;
    pdwPendingList = (ssipendingitem**)SAFE_REALLOC(pdwPendingList, nPendingSize * sizeof(ssipendingitem*));
  }

  pdwPendingList[nPendingCount] = (ssipendingitem*)SAFE_MALLOC(sizeof(ssipendingitem));
  pdwPendingList[nPendingCount]->hContact = hContact;

  nPendingCount++;
  LeaveCriticalSection(&servlistMutex);

  return bRes;
}



// Check if any pending operation is in progress
// If yes, get its data and remove it from queue
void RemovePendingOperation(HANDLE hContact, int nResult)
{
  int i, j;
  ssipendingitem* pItem = NULL;

  EnterCriticalSection(&servlistMutex);
  if (pdwPendingList)
  {
    for (i = 0; i<nPendingCount; i++)
    {
      if (pdwPendingList[i]->hContact == hContact)
      {
        pItem = pdwPendingList[i];
        for (j = i+1; j<nPendingCount; j++)
        {
          pdwPendingList[j-1] = pdwPendingList[j];
        }
        nPendingCount--;
        if (nResult) // we succeded, go on, resume operation
        {
          LeaveCriticalSection(&servlistMutex);

          if (pItem->ofCallback)
          {
            NetLog_Server("Resuming postponed operation.");

            makeGroupId(pItem->szGroupPath, pItem->ofCallback, pItem->pCookie);
          }
          else if ((int)pItem->pCookie == 1)
          {
            NetLog_Server("Resuming postponed update.");

            updateServContact(hContact);
          }

          SAFE_FREE(&pItem->szGroupPath); // free the string
          SAFE_FREE(&pItem);
          return;
        } // else remove all pending operations for this contact
        NetLog_Server("Purging postponed operation.");
        if ((pItem->pCookie) && ((int)pItem->pCookie != 1))
          SAFE_FREE(&pItem->pCookie->szGroupName); // do not leak nick name on error
        SAFE_FREE(&pItem->szGroupPath);
        SAFE_FREE(&pItem);
      }
    }
  }
  LeaveCriticalSection(&servlistMutex);
  return;
}



// Remove All pending operations
void FlushPendingOperations()
{
  int i;

  EnterCriticalSection(&servlistMutex);

  for (i = 0; i<nPendingCount; i++)
  {
    SAFE_FREE((void**)&pdwPendingList[i]);
  }
  SAFE_FREE((void**)&pdwPendingList);
  nPendingCount = 0;
  nPendingSize = 0;

  LeaveCriticalSection(&servlistMutex);
}



// 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 ReserveServerID(WORD wID, int bGroupId)
{
  EnterCriticalSection(&servlistMutex);
  if (nIDListCount >= nIDListSize)
  {
    nIDListSize += 100;
    pwIDList = (DWORD*)SAFE_REALLOC(pwIDList, nIDListSize * sizeof(DWORD));
  }

  pwIDList[nIDListCount] = wID | bGroupId << 0x18;
  nIDListCount++;  
  LeaveCriticalSection(&servlistMutex);
}



// Remove a server ID from the list of reserved IDs.
// Used for deleting contacts and other modifications.
void FreeServerID(WORD wID, int bGroupId)
{
  int i, j;
  DWORD dwId = wID | bGroupId << 0x18;

  EnterCriticalSection(&servlistMutex);
  if (pwIDList)
  {
    for (i = 0; i<nIDListCount; i++)
    {
      if (pwIDList[i] == dwId)
      { // we found it, so remove
        for (j = i+1; j<nIDListCount; j++)
        {
          pwIDList[j-1] = pwIDList[j];
        }
        nIDListCount--;
      }
    }
  }
  LeaveCriticalSection(&servlistMutex);
}


// Returns true if dwID is reserved
BOOL CheckServerID(WORD wID, unsigned int wCount)
{
  int i;

  EnterCriticalSection(&servlistMutex);
  if (pwIDList)
  {
    for (i = 0; i<nIDListCount; i++)
    {
      if (((pwIDList[i] & 0xFFFF) >= wID) && ((pwIDList[i] & 0xFFFF) <= wID + wCount))
      {
        LeaveCriticalSection(&servlistMutex);
        return TRUE;
      }
    }
  }
  LeaveCriticalSection(&servlistMutex);

  return FALSE;
}



void FlushServerIDs()
{
  EnterCriticalSection(&servlistMutex);
  SAFE_FREE(&pwIDList);
  nIDListCount = 0;
  nIDListSize = 0;
  LeaveCriticalSection(&servlistMutex);
}



static int GroupReserveIdsEnumProc(const char *szSetting,LPARAM lParam)
{ 
  if (szSetting && strlennull(szSetting)<5)
  { // it is probably server group
    char val[MAX_PATH+2]; // dummy
    DBVARIANT dbv;
    DBCONTACTGETSETTING cgs;

    dbv.type = DBVT_ASCIIZ;
    dbv.pszVal = val;
    dbv.cchVal = MAX_PATH;

    cgs.szModule=(char*)lParam;
    cgs.szSetting=szSetting;
    cgs.pValue=&dbv;
    if (CallService(MS_DB_CONTACT_GETSETTINGSTATIC,(WPARAM)NULL,(LPARAM)&cgs))
    { // we failed to read setting, try also utf8 - DB bug
      dbv.type = DBVT_UTF8;
      dbv.pszVal = val;
      dbv.cchVal = MAX_PATH;
      if (CallService(MS_DB_CONTACT_GETSETTINGSTATIC,(WPARAM)NULL,(LPARAM)&cgs))
        return 0; // we failed also, invalid setting
    }
    if (dbv.type!=DBVT_ASCIIZ)
    { // it is not a cached server-group name
      return 0;
    }
    ReserveServerID((WORD)strtoul(szSetting, NULL, 0x10), SSIT_GROUP);
#ifdef _DEBUG
    NetLog_Server("Loaded group %u:'%s'", strtoul(szSetting, NULL, 0x10), val);
#endif
  }
  return 0;
}



int ReserveServerGroups()
{
  DBCONTACTENUMSETTINGS dbces;
  int nStart = nIDListCount;

  char szModule[MAX_PATH+9];

  strcpy(szModule, gpszICQProtoName);
  strcat(szModule, "SrvGroups");

  dbces.pfnEnumProc = &GroupReserveIdsEnumProc;
  dbces.szModule = szModule;
  dbces.lParam = (LPARAM)szModule;

  CallService(MS_DB_CONTACT_ENUMSETTINGS, (WPARAM)NULL, (LPARAM)&dbces);

  return nIDListCount - nStart;
}



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

  EnterCriticalSection(&servlistMutex);
  if (wSrvID = ICQGetContactSettingWord(NULL, "SrvAvatarID", 0))
    ReserveServerID(wSrvID, SSIT_ITEM);
  if (wSrvID = ICQGetContactSettingWord(NULL, "SrvPhotoID", 0))
    ReserveServerID(wSrvID, SSIT_ITEM);
  if (wSrvID = ICQGetContactSettingWord(NULL, "SrvVisibilityID", 0))
    ReserveServerID(wSrvID, SSIT_ITEM);

  nGroups = ReserveServerGroups();

  hContact = ICQFindFirstContact();

  while (hContact)
  { // search all our contacts, reserve their server IDs
    if (wSrvID = ICQGetContactSettingWord(hContact, "ServerId", 0))
    {
      ReserveServerID(wSrvID, SSIT_ITEM);
      nContacts++;
    }
    if (wSrvID = ICQGetContactSettingWord(hContact, "SrvDenyId", 0))
    {
      ReserveServerID(wSrvID, SSIT_ITEM);
      nDenys++;
    }
    if (wSrvID = ICQGetContactSettingWord(hContact, "SrvPermitId", 0))
    {
      ReserveServerID(wSrvID, SSIT_ITEM);
      nPermits++;
    }
    if (wSrvID = ICQGetContactSettingWord(hContact, "SrvIgnoreId", 0))
    {
      ReserveServerID(wSrvID, SSIT_ITEM);
      nIgnores++;
    }

    hContact = ICQFindNextContact(hContact);
  }
  LeaveCriticalSection(&servlistMutex);

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

  return;
}



WORD GenerateServerId(int bGroupId)
{
  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, 0))
      break;
  }

  ReserveServerID(wId, bGroupId);

  return wId;
}

void ResetUserSSISettings(HANDLE hContact)
{
	DBWriteContactSettingWord(hContact, gpszICQProtoName, "ServerId", 0);
	DBWriteContactSettingWord(hContact, gpszICQProtoName, "SrvGroupId", 0);
	DBWriteContactSettingWord(hContact, gpszICQProtoName, "SrvPermitId", 0);
	DBWriteContactSettingWord(hContact, gpszICQProtoName, "SrvDenyId", 0);
	DBWriteContactSettingByte(hContact, gpszICQProtoName, "Auth", 0);
}


void ResetAllSSISettings(void)
{

	HANDLE hContact;
	int ID = 0;

	while (GetFromCacheByID(ID++, &hContact, NULL))
	{
		ResetUserSSISettings(hContact);
	}
	DBWriteContactSettingWord(NULL, gpszICQProtoName, "SrvAvatarID", 0);
	DBWriteContactSettingWord(NULL, gpszICQProtoName, "SrvVisibilityID", 0);
	DBWriteContactSettingWord(NULL, gpszICQProtoName, "SrvDefGroupId", 0);
	DBWriteContactSettingWord(NULL, gpszICQProtoName, "SrvRecordCount", 0);
	DBWriteContactSettingWord(NULL, gpszICQProtoName, "SrvImportId", 0);
	DBWriteContactSettingDword(NULL, gpszICQProtoName, "ImportTS", 0);

	// reset only if we reload list
	FlushServerIDs();

}


// Generate server ID with wCount IDs free after it, for sub-groups.
WORD GenerateServerIdPair(int bGroupId, 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, bGroupId);

  return wId;
}


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


static DWORD icq_sendServerItem(DWORD dwCookie, WORD wAction, WORD wGroupId, WORD wItemId, const char *szName, BYTE *pTLVs, int nTlvLength, WORD wItemType)
{ // 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));
  packFNACHeaderFull(&packet, ICQ_LISTS_FAMILY, wAction, 0, dwCookie);
  packWord(&packet, (WORD)nNameLen);
  if (nNameLen) 
    packBuffer(&packet, szName, (WORD)nNameLen);
  packWord(&packet, wGroupId);
  packWord(&packet, wItemId);   
  packWord(&packet, wItemType); 
  packWord(&packet, wTLVlen);
  if (wTLVlen)
    packBuffer(&packet, pTLVs, wTLVlen);

  // Send the packet and return the cookie
  sendServPacket(&packet);

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

  return dwCookie;
}



DWORD icq_sendServerContact(HANDLE hContact, DWORD dwCookie, WORD wAction, WORD wGroupId, WORD wContactId)
{
  DWORD dwUin;
  uid_str szUid;
  icq_packet pBuffer;
  char *szNick = NULL, *szNote = NULL;
  BYTE *pData = NULL;
  int nNickLen, nNoteLen, nDataLen;
  WORD wTLVlen;
  BYTE bAuth;
  int bDataTooLong = FALSE;

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

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

  {
    DBVARIANT dbv;

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

      ICQFreeVariant(&dbv);
    }
    else
    {
      pData = NULL;
      nDataLen = 0;
    }
  }

  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, "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;

  // 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, szNick);  // Nickname TLV

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

  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(&szNick);
  SAFE_FREE(&szNote);

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



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



DWORD icq_sendGroupUtf(DWORD dwCookie, WORD wAction, WORD wGroupId, const char *szName, void *pContent, int cbContent)
{
  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)
  {
    NetLog_Server("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, pContent);  // Groups TLV

  return icq_sendServerItem(dwCookie, wAction, wGroupId, 0, szName, pBuffer.pData, wTLVlen, SSI_ITEM_GROUP);
}



DWORD icq_modifyServerPrivacyItem(HANDLE hContact, DWORD dwUin, char* szUid, WORD wAction, DWORD dwOperation, WORD wItemId, WORD wType)
{
  servlistcookie* ack;
  DWORD dwCookie;

  if (!(ack = (servlistcookie*)SAFE_MALLOC(sizeof(servlistcookie))))
  { // cookie failed, use old fake
    dwCookie = GenerateCookie(wAction);
  }
  else
  {
    ack->dwAction = dwOperation; // remove privacy item
    ack->dwUin = dwUin;
    ack->hContact = hContact;
    ack->wContactId = wItemId;

    dwCookie = AllocateCookie(CKT_SERVERLIST, wAction, hContact, ack);
  }
  return icq_sendSimpleItem(dwCookie, wAction, dwUin, szUid, 0, wItemId, wType);
}



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



DWORD icq_addServerPrivacyItem(HANDLE 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 ---
 *
 */

static int GroupNamesEnumProc(const char *szSetting,LPARAM lParam)
{ // if we got pointer, store setting name, return zero
  if (lParam)
  {
    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 DeleteModuleEntries(const char* szModule)
{
  DBCONTACTENUMSETTINGS dbces;
  char** list = NULL;

  dbces.pfnEnumProc = &GroupNamesEnumProc;
  dbces.szModule = szModule;
  dbces.lParam = (LPARAM)&list;
  CallService(MS_DB_CONTACT_ENUMSETTINGS, (WPARAM)NULL, (LPARAM)&dbces);
  while (list)
  {
    void* bet;

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



int IsServerGroupsDefined()
{
  int iRes = 1;

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

    strcpy(szModule, gpszICQProtoName);
    strcat(szModule, "Groups"); // flush obsolete linking data
    DeleteModuleEntries(szModule);

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

  return iRes;
}



void FlushSrvGroupsCache()
{
  char szModule[MAX_PATH+9];

  strcpy(szModule, gpszICQProtoName);
  strcat(szModule, "SrvGroups");
  DeleteModuleEntries(szModule);
}



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

  hContact = ICQFindFirstContact();

  while (hContact)
  { // search all contacts
    if (wGroupID == ICQGetContactSettingWord(hContact, "SrvGroupId", 0))
    { // add only buddys from specified group
      wItemID = ICQGetContactSettingWord(hContact, "ServerId", 0);

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

    hContact = ICQFindNextContact(hContact);
  }

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



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

  hContact = ICQFindFirstContact();

  while (hContact)
  { // search all contacts
    if (wGroupID = ICQGetContactSettingWord(hContact, "SrvGroupId", 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 = ICQFindNextContact(hContact);
  }

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



static int GroupLinksEnumProc(const char *szSetting,LPARAM lParam)
{ // check link target, add if match
  if (DBGetContactSettingWord(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 removeGroupPathLinks(WORD wGroupID)
{ // remove miranda grouppath links targeting to this groupid
  DBCONTACTENUMSETTINGS dbces;
  char szModule[MAX_PATH+6];
  char* pars[3];

  strcpy(szModule, gpszICQProtoName);
  strcat(szModule, "Groups");

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

  dbces.pfnEnumProc = &GroupLinksEnumProc;
  dbces.szModule = szModule;
  dbces.lParam = (LPARAM)pars;

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

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



char* getServerGroupNameUtf(WORD wGroupID)
{
  char szModule[MAX_PATH+9];
  char szGroup[16];

  strcpy(szModule, gpszICQProtoName);
  strcat(szModule, "SrvGroups");
  _itoa(wGroupID, szGroup, 0x10);

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

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



void setServerGroupNameUtf(WORD wGroupID, const char* szGroupNameUtf)
{
  char szModule[MAX_PATH+9];
  char szGroup[16];

  strcpy(szModule, gpszICQProtoName);
  strcat(szModule, "SrvGroups");
  _itoa(wGroupID, szGroup, 0x10);

  if (szGroupNameUtf)
    UniWriteContactSettingUtf(NULL, szModule, szGroup, (char*)szGroupNameUtf);
  else
  {
    DBDeleteContactSetting(NULL, szModule, szGroup);
    removeGroupPathLinks(wGroupID);
  }
  return;
}
 


WORD getServerGroupIDUtf(const char* szPath)
{
  char szModule[MAX_PATH+6];
  WORD wGroupId;

  strcpy(szModule, gpszICQProtoName);
  strcat(szModule, "Groups");

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

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

  return wGroupId;
}



void setServerGroupIDUtf(const char* szPath, WORD wGroupID)
{
  char szModule[MAX_PATH+6];

  strcpy(szModule, gpszICQProtoName);
  strcat(szModule, "Groups");

  if (wGroupID)
    DBWriteContactSettingWord(NULL, szModule, szPath, wGroupID);
  else
    DBDeleteContactSetting(NULL, szModule, szPath);

  return;
}



// copied from groups.c - horrible, but only possible as this is not available as service
int GroupNameExistsUtf(const char *name,int skipGroup)
{
  char idstr[33];
  char* szGroup = NULL;
  int i;

  if (name == NULL) return 1; // no group always exists
  for(i=0;;i++)
  {
    if(i==skipGroup) continue;
    itoa(i,idstr,10);
    szGroup = UniGetContactSettingUtf(NULL, "CListGroups", idstr, "");
    if (!strlennull(szGroup)) break;
    if (!strcmpnull(szGroup+1, name)) 
    { // caution, this can be false - with ansi clist
      SAFE_FREE(&szGroup);
      return 1;
    }
    SAFE_FREE(&szGroup);
  }
  SAFE_FREE(&szGroup);
  return 0;
}



// 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;
}



int countGroupLevel(WORD wGroupId)
{
  char* szGroupName = getServerGroupNameUtf(wGroupId);
  int cnt = -1;

  if (szGroupName)
    cnt = countGroupNameLevel(szGroupName);

  return cnt;
}



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 CreateCListGroup(const char* szGroupName)
{
  int hGroup;
  CLIST_INTERFACE *clint = NULL;

  if (ServiceExists(MS_CLIST_RETRIEVE_INTERFACE))
    clint = (CLIST_INTERFACE*)CallService(MS_CLIST_RETRIEVE_INTERFACE, 0, 0);

  hGroup = CallService(MS_CLIST_GROUPCREATE, 0, 0);

  if (gbUnicodeCore && clint && clint->version >= 1)
  { // we've got unicode interface, use it
    wchar_t* usTmp = make_unicode_string(szGroupName);

    clint->pfnRenameGroup(hGroup, (TCHAR*)usTmp);
    SAFE_FREE(&usTmp);
  }
  else
  { // old ansi version - no other way
    int size = strlennull(szGroupName) + 2;
    char* szTmp = (char*)_alloca(size);

    utf8_decode_static(szGroupName, szTmp, size);
    CallService(MS_CLIST_GROUPRENAME, hGroup, (LPARAM)szTmp);
  }

  return hGroup;
}



// demangle group path
char* makeGroupPathUtf(WORD wGroupId)
{
  char* szGroup = NULL;

  if (szGroup = getServerGroupNameUtf(wGroupId))
  { // this groupid is not valid
    while (strstr(szGroup, "\\")!=NULL) *strstr(szGroup, "\\") = '_'; // remove invalid char
    if (getServerGroupIDUtf(szGroup) == wGroupId)
    { // this grouppath is known and is for this group, set user group
      return szGroup;
    }
    else
    {
      if (strlennull(szGroup) && (szGroup[0] == '>'))
      { // it is probably a sub-group
        WORD wId = wGroupId-1;
        int level = countGroupLevel(wGroupId);
        int levnew = countGroupLevel(wId);
        char* szTempGroup;

        if (level == -1)
        { // this is just an ordinary group
          int hGroup;

          if (!GroupNameExistsUtf(szGroup, -1))
          { // if the group does not exist, create it
            hGroup = CreateCListGroup(szGroup);
          }
          setServerGroupIDUtf(szGroup, wGroupId); // set grouppath id
          return szGroup;
        }
        while ((levnew >= level) && (levnew != -1))
        { // we look for parent group
          wId--;
          levnew = countGroupLevel(wId);
        }
        if (levnew == -1)
        { // that was not a sub-group, it was just a group starting with >
          if (!GroupNameExistsUtf(szGroup, -1))
          { // if the group does not exist, create it
            int hGroup = CreateCListGroup(szGroup);
          }
          setServerGroupIDUtf(szGroup, wGroupId); // set grouppath id
          return szGroup;
        }

        szTempGroup = makeGroupPathUtf(wId);

        szTempGroup = SAFE_REALLOC(szTempGroup, strlennull(szGroup)+strlennull(szTempGroup)+2);
        strcat(szTempGroup, "\\");
        strcat(szTempGroup, szGroup+level);
        SAFE_FREE(&szGroup);
        szGroup = szTempGroup;
        
        if (getServerGroupIDUtf(szGroup) == wGroupId)
        { // known path, give
          return szGroup;
        }
        else
        { // unknown path, create
          if (!GroupNameExistsUtf(szGroup, -1))
          { // if the group does not exist, create it
            int hGroup = CreateCListGroup(szGroup);
          }
          setServerGroupIDUtf(szGroup, wGroupId); // set grouppath id
          return szGroup;
        }
      }
      else
      { // create that group
        int hGroup;

        if (!GroupNameExistsUtf(szGroup, -1))
        { // if the group does not exist, create it
          hGroup = CreateCListGroup(szGroup);
        }
        setServerGroupIDUtf(szGroup, wGroupId); // set grouppath id
        return szGroup;
      }
    }
  }
  return NULL;
}



// this is the second pard of recursive event-driven procedure
void madeMasterGroupId(WORD wGroupID, LPARAM lParam)
{
  servlistcookie* clue = (servlistcookie*)lParam;
  char* szGroup = clue->szGroupName;
  GROUPADDCALLBACK ofCallback = clue->ofCallback;
  servlistcookie* param = (servlistcookie*)clue->lParam;
  int level;
  
  if (wGroupID) // if we got an id count level
    level = countGroupLevel(wGroupID);
  else
    level = -1;

  SAFE_FREE(&clue);

  if (level == -1)
  { // something went wrong, give the id and go away
    if (ofCallback) ofCallback(wGroupID, (LPARAM)param);

    SAFE_FREE(&szGroup);
    return;
  }
  level++; // we are a sub

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

  if (!CheckServerID((WORD)(wGroupID+1), 0))
  { // the next id is free, so create our group with that id
    servlistcookie* ack;
    DWORD dwCookie;
    char* szSubGroup = (char*)SAFE_MALLOC(strlennull(szGroup)+level+1);

    if (szSubGroup)
    {
      int i;

      for (i=0; i<level; i++)
      {
        szSubGroup[i] = '>';
      }
      strcpy(szSubGroup+level, szGroup);
      szSubGroup[strlennull(szGroup)+level] = '\0';

      if (ack = (servlistcookie*)SAFE_MALLOC(sizeof(servlistcookie)))
      { // we have cookie good, go on
        ReserveServerID((WORD)(wGroupID+1), SSIT_GROUP);
        
        ack->wGroupId = wGroupID+1;
        ack->szGroupName = szSubGroup; // we need that name
        ack->dwAction = SSA_GROUP_ADD;
        ack->ofCallback = ofCallback;
        ack->lParam = (LPARAM)param;
        dwCookie = AllocateCookie(CKT_SERVERLIST, ICQ_LISTS_ADDTOLIST, 0, ack);

        sendAddStart(0);
        icq_sendGroupUtf(dwCookie, ICQ_LISTS_ADDTOLIST, ack->wGroupId, szSubGroup, NULL, 0);

        SAFE_FREE(&szGroup);
        return;
      }
      SAFE_FREE(&szSubGroup);
    }
  }
  // we failed to create sub-group give parent groupid
  if (ofCallback) ofCallback(wGroupID, (LPARAM)param);

  SAFE_FREE(&szGroup);
  return;
}



// create group with this path, a bit complex task
// this supposes that all server groups are known
WORD makeGroupId(const char* szGroupPath, GROUPADDCALLBACK ofCallback, servlistcookie* lParam)
{
  WORD wGroupID = 0;
  char* szGroup = (char*)szGroupPath;

  if (!szGroup || szGroup[0]=='\0') szGroup = DEFAULT_SS_GROUP;

  if (wGroupID = getServerGroupIDUtf(szGroup))
  {
    if (ofCallback) ofCallback(wGroupID, (LPARAM)lParam);
    return wGroupID; // if the path is known give the id
  }

  if (!strstr(szGroup, "\\"))
  { // a root group can be simply created without problems
    servlistcookie* ack;
    DWORD dwCookie;

    if (ack = (servlistcookie*)SAFE_MALLOC(sizeof(servlistcookie)))
    { // we have cookie good, go on
      ack->wGroupId = GenerateServerId(SSIT_GROUP);
      ack->szGroupName = null_strdup(szGroup); // we need that name
      ack->dwAction = SSA_GROUP_ADD;
      ack->ofCallback = ofCallback;
      ack->lParam = (LPARAM)lParam;
      dwCookie = AllocateCookie(CKT_SERVERLIST, ICQ_LISTS_ADDTOLIST, 0, ack);

      sendAddStart(0);
      icq_sendGroupUtf(dwCookie, ICQ_LISTS_ADDTOLIST, ack->wGroupId, szGroup, NULL, 0);

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

    if (strstr(szSub, "\\") != NULL)
    { // determine parent group
      szLast = strstr(szSub, "\\")+1;

      while (strstr(szLast, "\\") != NULL)
        szLast = strstr(szLast, "\\")+1; // look for last backslash
      szLast[-1] = '\0'; 
    }
    // make parent group id
    ack = (servlistcookie*)SAFE_MALLOC(sizeof(servlistcookie));
    if (ack)
    {
      WORD wRes;
      ack->lParam = (LPARAM)lParam;
      ack->ofCallback = ofCallback;
      ack->szGroupName = null_strdup(szLast); // groupname
      wRes = makeGroupId(szSub, madeMasterGroupId, ack);
      SAFE_FREE(&szSub);

      return wRes;
    }

    SAFE_FREE(&szSub); 
  }
  
  if (strstr(szGroup, "\\") != NULL)
  { // we failed to get grouppath, trim it by one group
    WORD wRes;
    char *szLast = null_strdup(szGroup);
    char *szLess = szLast;

    while (strstr(szLast, "\\") != NULL)
      szLast = strstr(szLast, "\\")+1; // look for last backslash
    szLast[-1] = '\0'; 
    wRes = makeGroupId(szLess, ofCallback, lParam);
    SAFE_FREE(&szLess);

    return wRes;
  }

  wGroupID = 0; // everything failed, let callback handle error
  if (ofCallback) ofCallback(wGroupID, (LPARAM)lParam);
  
  return wGroupID;
}


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

void addServContactReady(WORD wGroupID, LPARAM lParam)
{
  WORD wItemID;
  DWORD dwUin;
  uid_str szUid;
  servlistcookie* ack;
  DWORD dwCookie;

  ack = (servlistcookie*)lParam;

  if (!ack || !wGroupID) // something went wrong
  {
    if (ack) RemovePendingOperation(ack->hContact, 0);
    return;
  }

  wItemID = ICQGetContactSettingWord(ack->hContact, "ServerId", 0);

  if (wItemID)
  { // Only add the contact if it doesnt already have an ID
    RemovePendingOperation(ack->hContact, 0);
    NetLog_Server("Failed to add contact to server side list (%s)", "already there");
    return;
  }

  // Get UID
  if (ICQGetContactSettingUID(ack->hContact, &dwUin, &szUid))
  { // Could not do anything without uid
    RemovePendingOperation(ack->hContact, 0);
    NetLog_Server("Failed to add contact to server side list (%s)", "no UID");
    return;
  }

  wItemID = GenerateServerId(SSIT_ITEM);

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

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

  sendAddStart(0);
  icq_sendServerContact(ack->hContact, dwCookie, ICQ_LISTS_ADDTOLIST, wGroupID, wItemID);
  ICQWriteContactSettingByte(ack->hContact,"CheckSelfRemove", 0);//checkselfremove
}



// Called when contact should be added to server list, if group does not exist, create one
DWORD addServContact(HANDLE hContact, const char *pszGroup)
{
  servlistcookie* ack;

  if (!(ack = (servlistcookie*)SAFE_MALLOC(sizeof(servlistcookie))))
  { // Could not do anything without cookie
    NetLog_Server("Failed to add contact to server side list (%s)", "malloc failed");
    return 0;
  }
  else
  {
    ack->hContact = hContact;

    if (AddPendingOperation(hContact, pszGroup, ack, addServContactReady))
      makeGroupId(pszGroup, addServContactReady, ack);

    return 1;
  }
}



// Called when contact should be removed from server list, remove group if it remain empty
DWORD removeServContact(HANDLE hContact)
{
  WORD wGroupID;
  WORD wItemID;
  DWORD dwUin;
  uid_str szUid;
  servlistcookie* ack;
  DWORD dwCookie;

  // Get the contact's group ID
  if (!(wGroupID = ICQGetContactSettingWord(hContact, "SrvGroupId", 0)))
  {
    // Could not find a usable group ID
    NetLog_Server("Failed to remove contact from server side list (%s)", "no group ID");
    return 0;
  }

  // Get the contact's item ID
  if (!(wItemID = ICQGetContactSettingWord(hContact, "ServerId", 0)))
  {
    // Could not find usable item ID
    NetLog_Server("Failed to remove contact from server side list (%s)", "no item ID");
    return 0;
  }

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

  if (!(ack = (servlistcookie*)SAFE_MALLOC(sizeof(servlistcookie))))
  { // Could not do anything without cookie
    NetLog_Server("Failed to remove contact from server side list (%s)", "malloc failed");
    return 0;
  }
  else
  {
    ack->dwAction = SSA_CONTACT_REMOVE;
    ack->dwUin = dwUin;
    ack->hContact = hContact;
    ack->wGroupId = wGroupID;
    ack->wContactId = wItemID;

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

  sendAddStart(0);
  icq_sendServerContact(hContact, dwCookie, ICQ_LISTS_REMOVEFROMLIST, wGroupID, wItemID);

  return 0;
}



void moveServContactReady(WORD wNewGroupID, LPARAM lParam)
{
  WORD wItemID;
  WORD wGroupID;
  DWORD dwUin;
  uid_str szUid;
  servlistcookie* ack;
  DWORD dwCookie, dwCookie2;

  ack = (servlistcookie*)lParam;

  if (!ack || !wNewGroupID) // something went wrong
  {
    if (ack) RemovePendingOperation(ack->hContact, 0);
    return;
  }

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

  wItemID = ICQGetContactSettingWord(ack->hContact, "ServerId", 0);
  wGroupID = ICQGetContactSettingWord(ack->hContact, "SrvGroupId", 0);

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

  if (!wGroupID)
  { // Only move the contact if it had an GroupID
    RemovePendingOperation(ack->hContact, 0);
    NetLog_Server("Failed to move contact to group on server side list (%s)", "no Group");
    return;
  }

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

  // Get UID
  if (ICQGetContactSettingUID(ack->hContact, &dwUin, &szUid))
  { // Could not do anything without uin
    RemovePendingOperation(ack->hContact, 0);
    NetLog_Server("Failed to move contact to group on server side list (%s)", "no UID");
    return;
  }

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

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

  sendAddStart(0);
  // imitate icq5, previously here was different order, but AOL changed and it ceased to work
  icq_sendServerContact(ack->hContact, dwCookie, ICQ_LISTS_REMOVEFROMLIST, wGroupID, wItemID);
  icq_sendServerContact(ack->hContact, dwCookie2, ICQ_LISTS_ADDTOLIST, wNewGroupID, ack->wNewContactId);
}



// Called when contact should be moved from one group to another, create new, remove empty
DWORD moveServContactGroup(HANDLE hContact, const char *pszNewGroup)
{
  servlistcookie* ack;

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

  if (!ICQGetContactSettingWord(hContact, "ServerId", 0))
  { // the contact is not stored on the server, check if we should try to add
    if (!ICQGetContactSettingByte(NULL, "ServerAddRemove", DEFAULT_SS_ADDSERVER) ||
      DBGetContactSettingByte(hContact, "CList", "Hidden", 0))
      return 0;
  }

  if (!(ack = (servlistcookie*)SAFE_MALLOC(sizeof(servlistcookie))))
  { // Could not do anything without cookie
    NetLog_Server("Failed to add contact to server side list (%s)", "malloc failed");
    return 0;
  }
  else
  {
    ack->hContact = hContact;

    if (AddPendingOperation(hContact, pszNewGroup, ack, moveServContactReady))
      makeGroupId(pszNewGroup, moveServContactReady, ack);
    return 1;
  }
}



// Is called when a contact' details has been changed locally to update
// the server side details.
static DWORD updateServContact(HANDLE hContact)
{
  WORD wGroupID;
  WORD wItemID;
  DWORD dwUin;
  uid_str szUid;
  servlistcookie* ack;
  DWORD dwCookie;

  // Get the contact's group ID
  if (!(wGroupID = ICQGetContactSettingWord(hContact, "SrvGroupId", 0)))
  {
    // Could not find a usable group ID
    NetLog_Server("Failed to update contact's details on server side list (%s)", "no group ID");
    RemovePendingOperation(hContact, 0);
    return 0;
  }

  // Get the contact's item ID
  if (!(wItemID = ICQGetContactSettingWord(hContact, "ServerId", 0)))
  {
    // Could not find usable item ID
    NetLog_Server("Failed to update contact's details on server side list (%s)", "no item ID");
    RemovePendingOperation(hContact, 0);
    return 0;
  }

  // Get UID
  if (ICQGetContactSettingUID(hContact, &dwUin, &szUid))
  {
    // Could not set nickname on server without uid
    NetLog_Server("Failed to update contact's details on server side list (%s)", "no UID");
    RemovePendingOperation(hContact, 0);
    return 0;
  }
  
  if (!(ack = (servlistcookie*)SAFE_MALLOC(sizeof(servlistcookie))))
  {
    // Could not allocate cookie - use old fake
    NetLog_Server("Failed to allocate cookie");
    dwCookie = GenerateCookie(ICQ_LISTS_UPDATEGROUP);
  }
  else
  {
    ack->dwAction = SSA_CONTACT_UPDATE;
    ack->wContactId = wItemID;
    ack->wGroupId = wGroupID;
    ack->dwUin = dwUin;
    ack->hContact = hContact;

    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);

  return dwCookie;
}



void renameServGroup(WORD wGroupId, char* szGroupName)
{
  servlistcookie* ack;
  DWORD dwCookie;
  char* szGroup, *szLast;
  int level = countGroupLevel(wGroupId);
  int i;
  void* groupData;
  DWORD groupSize;

  if (IsGroupRenamed(wGroupId)) return; // the group was already renamed

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

  szLast = szGroupName;
  i = level;
  while (i)
  { // find correct part of grouppath
    szLast = strstr(szLast, "\\")+1;
    i--;
  }
  szGroup = (char*)SAFE_MALLOC(strlennull(szLast)+1+level);
  if (!szGroup) return;

  for (i=0;i<level;i++)
  { // create level prefix
    szGroup[i] = '>';
  }
  strcat(szGroup, szLast);
  // truncate other possible sub-groups
  szLast = strstr(szGroup, "\\");
  if (szLast)
    szLast[0] = '\0';

  if (!(ack = (servlistcookie*)SAFE_MALLOC(sizeof(servlistcookie))))
  { // cookie failed, use old fake
    dwCookie = GenerateCookie(ICQ_LISTS_UPDATEGROUP);
  }
  if (groupData = collectBuddyGroup(wGroupId, &groupSize))
  {
    ack->dwAction = SSA_GROUP_RENAME;
    ack->wGroupId = wGroupId;
    ack->szGroupName = szGroup; // we need this name

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

    AddGroupRename(wGroupId);

    icq_sendGroupUtf(dwCookie, ICQ_LISTS_UPDATEGROUP, wGroupId, szGroup, groupData, groupSize);
    SAFE_FREE(&groupData);
  }
}



void resetServContactAuthState(HANDLE hContact, DWORD dwUin)
{
  WORD wContactId = ICQGetContactSettingWord(hContact, "ServerId", 0);
  WORD wGroupId = ICQGetContactSettingWord(hContact, "SrvGroupId", 0);

  if (wContactId && wGroupId)
  {
    DWORD dwCookie;
    servlistcookie* ack;

    if (ack = (servlistcookie*)SAFE_MALLOC(sizeof(servlistcookie)))
    { // we have cookie good, go on
      ack->hContact = hContact;
      ack->wContactId = wContactId;
      ack->wGroupId = wGroupId;
      ack->dwAction = SSA_CONTACT_FIX_AUTH;
      ack->dwUin = dwUin;
      dwCookie = AllocateCookie(CKT_SERVERLIST, 0, hContact, ack);

      sendAddStart(0);
      icq_sendServerContact(hContact, dwCookie, ICQ_LISTS_REMOVEFROMLIST, wGroupId, wContactId);
      ICQDeleteContactSetting(hContact, "ServerData");
      icq_sendServerContact(hContact, dwCookie, ICQ_LISTS_ADDTOLIST, wGroupId, wContactId);
      sendAddEnd();
    }
  }
}



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



static int ServListDbSettingChanged(WPARAM wParam, LPARAM lParam)
{
  DBCONTACTWRITESETTING* cws = (DBCONTACTWRITESETTING*)lParam;

  // We can't upload changes to NULL contact
  if ((HANDLE)wParam == NULL)
    return 0;

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

  { // only our contacts will be handled
    if (IsICQContact((HANDLE)wParam))
      ;// our contact, fine; otherwise return
    else 
      return 0;
  }
  
  if (!strcmpnull(cws->szModule, "CList"))
  {
    // Has a temporary contact just been added permanently?
    if (!strcmpnull(cws->szSetting, "NotOnList") &&
      (cws->value.type == DBVT_DELETED || (cws->value.type == DBVT_BYTE && cws->value.bVal == 0)) &&
      ICQGetContactSettingByte(NULL, "ServerAddRemove", DEFAULT_SS_ADDSERVER) &&
      !DBGetContactSettingByte((HANDLE)wParam, "CList", "Hidden", 0))
    { // Add to server-list
      IcqAddServerContact(wParam, 0);
    }

    // Has contact been renamed?
    if (!strcmpnull(cws->szSetting, "MyHandle") &&
      ICQGetContactSettingByte(NULL, "StoreServerDetails", DEFAULT_SS_STORE))
    {
      if (AddPendingOperation((HANDLE)wParam, NULL, (servlistcookie*)1, NULL))
        updateServContact((HANDLE)wParam);
    }

    // Has contact been moved to another group?
    if (!strcmpnull(cws->szSetting, "Group") &&
      ICQGetContactSettingByte(NULL, "StoreServerDetails", DEFAULT_SS_STORE))
    { // Test if group was not renamed...
      WORD wGroupId = ICQGetContactSettingWord((HANDLE)wParam, "SrvGroupId", 0);
      char* szGroup = makeGroupPathUtf(wGroupId);
      char* szNewGroup;
      int bRenamed = 0;
      int bMoved = 1;

      // Read group from DB
      szNewGroup = UniGetContactSettingUtf((HANDLE)wParam, "CList", "Group", NULL);

      if (szNewGroup && wGroupId && !GroupNameExistsUtf(szGroup, -1))
      { // if we moved from non-existing group, it can be rename
        if (!getServerGroupIDUtf(szNewGroup))
        { // the target group is not known - it is probably rename
          if (getServerGroupIDUtf(szGroup))
          { // source group not known -> already renamed
            if (countClistGroupLevel(szNewGroup) == countGroupLevel(wGroupId))
            { // renamed groups can be only in the same level, if not it is move
              if (!IsGroupRenamed(wGroupId))
              { // is rename in progress ?
                bRenamed = 1; // TODO: we should really check if group was not moved to sub-group
                NetLog_Server("Group %x renamed to ""%s"".", wGroupId, szNewGroup);
              }
              else // if rename in progress do not move contacts
                bMoved = 0;
            }
          }
        }
      }
      SAFE_FREE(&szGroup);

      if (bRenamed)
        renameServGroup(wGroupId, szNewGroup);
      else if (bMoved) // TODO: this is bad, we badly need rate management
        moveServContactGroup((HANDLE)wParam, szNewGroup);

      SAFE_FREE(&szNewGroup);
    }
  }

  if (!strcmpnull(cws->szModule, "UserInfo"))
  {
    if (!strcmpnull(cws->szSetting, "MyNotes") &&
      ICQGetContactSettingByte(NULL, "StoreServerDetails", DEFAULT_SS_STORE))
    {
      if (AddPendingOperation((HANDLE)wParam, NULL, (servlistcookie*)1, NULL))
        updateServContact((HANDLE)wParam);
    }
  }

  return 0;
}



static int ServListDbContactDeleted(WPARAM wParam, LPARAM lParam)
{
  DeleteFromCache((HANDLE)wParam);

  if (!icqOnline && gbSsiEnabled)
  { // contact was deleted only locally - retrieve full list on next connect
    ICQWriteContactSettingWord((HANDLE)wParam, "SrvRecordCount", 0);
  }

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

  { // we need all server contacts on local buddy list
    WORD wContactID;
    WORD wGroupID;
    WORD wVisibleID;
    WORD wInvisibleID;
    WORD wIgnoreID;
    DWORD dwUIN;
    uid_str szUID;

    wContactID = ICQGetContactSettingWord((HANDLE)wParam, "ServerId", 0);
    wGroupID = ICQGetContactSettingWord((HANDLE)wParam, "SrvGroupId", 0);
    wVisibleID = ICQGetContactSettingWord((HANDLE)wParam, "SrvPermitId", 0);
    wInvisibleID = ICQGetContactSettingWord((HANDLE)wParam, "SrvDenyId", 0);
    wIgnoreID = ICQGetContactSettingWord((HANDLE)wParam, "SrvIgnoreId", 0);
    if (ICQGetContactSettingUID((HANDLE)wParam, &dwUIN, &szUID))
      return 0;

    // Close all opened peer connections
    CloseContactDirectConns((HANDLE)wParam);

    if ((wGroupID && wContactID) || wVisibleID || wInvisibleID || wIgnoreID)
    {
      if (wContactID)
      { // delete contact from server
        removeServContact((HANDLE)wParam);
      }

      if (wVisibleID)
      { // delete permit record
        icq_removeServerPrivacyItem((HANDLE)wParam, dwUIN, szUID, wVisibleID, SSI_ITEM_PERMIT);
      }

      if (wInvisibleID)
      { // delete deny record
        icq_removeServerPrivacyItem((HANDLE)wParam, dwUIN, szUID, wInvisibleID, SSI_ITEM_DENY);
      }

      if (wIgnoreID)
      { // delete ignore record
        icq_removeServerPrivacyItem((HANDLE)wParam, dwUIN, szUID, wIgnoreID, SSI_ITEM_IGNORE);
      }
    }
  }

  return 0;
}



void InitServerLists(void)
{
  InitializeCriticalSection(&servlistMutex);
  
  hHookSettingChanged = HookEvent(ME_DB_CONTACT_SETTINGCHANGED, ServListDbSettingChanged);
  hHookContactDeleted = HookEvent(ME_DB_CONTACT_DELETED, ServListDbContactDeleted);
}



void UninitServerLists(void)
{
  if (hHookSettingChanged)
    UnhookEvent(hHookSettingChanged);

  if (hHookContactDeleted)
    UnhookEvent(hHookContactDeleted);

  FlushServerIDs();
  FlushPendingOperations();

  DeleteCriticalSection(&servlistMutex);
}