summaryrefslogtreecommitdiff
path: root/protocols/ICQCorp/src/protocol.cpp
blob: ad23549195d03090adbb12294500a8149cf9871a (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
/*
	ICQ Corporate protocol plugin for Miranda IM.
	Copyright (C) 2003-2005 Eugene Tarasenko <zlyden13@inbox.ru>

	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.
	*/

#include "stdafx.h"

ICQ icq;

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

unsigned short toIcqStatus(unsigned short status)
{
	switch (status) {
	case ID_STATUS_OFFLINE: return ICQ_STATUS_OFFLINE;
	case ID_STATUS_ONLINE: return ICQ_STATUS_ONLINE;
	case ID_STATUS_AWAY: return ICQ_STATUS_AWAY;
	case ID_STATUS_DND: return ICQ_STATUS_DND;
	case ID_STATUS_NA: return ICQ_STATUS_NA;
	case ID_STATUS_OCCUPIED: return ICQ_STATUS_OCCUPIED;
	case ID_STATUS_FREECHAT: return ICQ_STATUS_FREECHAT;
	case ID_STATUS_INVISIBLE: return ICQ_STATUS_PRIVATE;
	}
	return ICQ_STATUS_ONLINE;
}

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

unsigned short toIdStatus(unsigned short status)
{
	switch (status) {
	case ICQ_STATUS_OFFLINE: return ID_STATUS_OFFLINE;
	case ICQ_STATUS_ONLINE: return ID_STATUS_ONLINE;
	case ICQ_STATUS_AWAY: return ID_STATUS_AWAY;
	case ICQ_STATUS_DND: return ID_STATUS_DND;
	case ICQ_STATUS_NA: return ID_STATUS_NA;
	case ICQ_STATUS_OCCUPIED: return ID_STATUS_OCCUPIED;
	case ICQ_STATUS_FREECHAT: return ID_STATUS_FREECHAT;
	case ICQ_STATUS_PRIVATE: return ID_STATUS_INVISIBLE;
	}
	return ID_STATUS_ONLINE;
}

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

LRESULT WINAPI messageWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	SOCKET hSocket = (SOCKET)wParam;
	unsigned short netEvents = LOWORD(lParam);
	unsigned long result;

	switch (msg) {
	case WM_NETEVENT_SERVER:
		if (hSocket == icq.udpSocket.handleVal) {
			if (netEvents & FD_READ)
				icq.recvUDP(0);
			break;
		}
		break;

	case WM_NETEVENT_CONNECTION:
		if (hSocket == icq.tcpSocket.handleVal) {
			if (netEvents & FD_ACCEPT)
				icq.recvNewTCP(0);
			break;
		}
		break;

	case WM_NETEVENT_USER:
		if (netEvents & FD_READ) {
			ioctlsocket(hSocket, FIONREAD, &result);
			if (result > 0) icq.recvTCP(hSocket);
		}
		if (netEvents & FD_CLOSE) {
			unsigned int i;
			for (i = 0; i < icqUsers.size(); i++) {
				if (hSocket == icqUsers[i]->socket.handleVal) {
					Netlib_Logf(hNetlibUser, "[tcp] user %d is aborted connection\n", icqUsers[i]->dwUIN);
					icqUsers[i]->socket.closeConnection();
					break;
				}
			}
		}
		break;

	case WM_NETEVENT_TRANSFER:
		if (netEvents & FD_READ) {
			ioctlsocket(hSocket, FIONREAD, &result);
			if (result > 0)
				icq.recvTransferTCP(hSocket);
		}
		if (netEvents & FD_CLOSE) {
			for (size_t i = 0; i < icqTransfers.size(); i++) {
				if (hSocket == icqTransfers[i]->socket.handleVal) {
					Netlib_Logf(hNetlibUser, "[tcp] user %d is aborted file connection\n", icqTransfers[i]->uin);
					ProtoBroadcastAck(protoName, icqTransfers[i]->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, icqTransfers[i], 0);
					delete icqTransfers[i];
					icqTransfers[i] = icqTransfers[icqTransfers.size() - 1];
					icqTransfers.pop_back();
					break;
				}
			}
		}
		break;

	default:
		return DefWindowProc(hWnd, msg, wParam, lParam);
	}

	return 0;
}

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

void WINAPI pingTimerProc(HWND, UINT, UINT_PTR, DWORD)
{
	icq.ping();
}

///////////////////////////////////////////////////////////////////////////////
//
//  ICQ
//
///////////////////////////////////////////////////////////////////////////////

ICQ::ICQ()
	: tcpSocket(WM_NETEVENT_CONNECTION),
	udpSocket(WM_NETEVENT_SERVER)
{}

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

bool ICQ::load()
{
	WSADATA data;

	if (WSAStartup(MAKEWORD(2, 2), &data)) {
		MessageBox(nullptr, TranslateT("ICQ Corporate plugin used only WinSock v2.2 or later."), _A2T(protoName), MB_ICONWARNING | MB_OK);
		return false;
	}

	statusVal = ID_STATUS_OFFLINE;
	searchSequenceVal = 0;
	tcpSequenceVal = 0xFFFFFFFE;

	awayMessage = new char[1];
	awayMessage[0] = 0;

	WNDCLASSA wc = { 0, messageWndProc, 0, 0, g_plugin.getInst(), nullptr, nullptr, nullptr, nullptr, protoName };
	if (!RegisterClassA(&wc))
		return false;

	hWnd = CreateWindowExA(0, protoName, nullptr, 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, g_plugin.getInst(), nullptr);
	if (hWnd == nullptr)
		return false;

	return true;
}

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

void ICQ::unload()
{
	if (statusVal != ID_STATUS_OFFLINE) logoff(false);

	KillTimer(nullptr, pingTimer);
	pingTimer = NULL;

	delete[] awayMessage;

	WSACleanup();

	DestroyWindow(hWnd);
	UnregisterClassA(protoName, g_plugin.getInst());
}

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

bool ICQ::logon(unsigned short logonStatus)
{
	DBVARIANT dbv;
	char str[128];

	if (!g_plugin.getString("Server", &dbv)) {
		lstrcpyA(str, dbv.pszVal);
		db_free(&dbv);
	}
	else {
		MessageBox(nullptr, TranslateT("You need specify ICQ Corporate login server."), _A2T(protoName), MB_ICONWARNING | MB_OK);
		return false;
	}

	if (!tcpSocket.connected() && !tcpSocket.startServer())
		return false;

	if (!udpSocket.connected()) {
		if (!udpSocket.setDestination(str, db_get_w(0, protoName, "Port", 4000)))
			return false;
		udpSocket.openConnection();
	}

	if (pingTimer == NULL)
		pingTimer = SetTimer(nullptr, 0, PING_FREQUENCY, pingTimerProc);

	updateContactList();

	dwUIN = g_plugin.getDword("UIN", 0);
	if (!g_plugin.getString("Password", &dbv)) {
		lstrcpyA(str, dbv.pszVal);
		db_free(&dbv);
	}

	timeStampLastMessage = 0;
	sequenceVal = 1;

	Packet loginPacket;
	loginPacket << ICQ_VERSION
		<< ICQ_CMDxSND_LOGON
		<< sequenceVal
		<< sequenceVal
		<< dwUIN
		<< (unsigned int)0x00
		<< tcpSocket.localPortVal
		<< str
		<< (unsigned short)0x7A
		<< (unsigned short)0x02
		//				<< LOCALHOST
		<< udpSocket.localIPVal
		<< (unsigned char)0x04
		<< (unsigned int)toIcqStatus(logonStatus)
		<< (unsigned int)0x02
		<< (unsigned int)0x00
		<< (unsigned short)0x13
		<< (unsigned short)0x7A;

	Netlib_Logf(hNetlibUser, "[udp] requesting logon (%d)...\n", sequenceVal);
	sendICQ(udpSocket, loginPacket, ICQ_CMDxSND_LOGON, sequenceVal);

	desiredStatus = logonStatus;
	statusVal = ID_STATUS_CONNECTING;
	ProtoBroadcastAck(protoName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)ID_STATUS_OFFLINE, statusVal);

	return true;
}

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

void ICQ::logoff(bool reconnect)
{
	unsigned int i;

	// if not connected then don't both logging off
	if (udpSocket.connected()) {
		Packet logoffPacket;
		logoffPacket << ICQ_VERSION
			<< ICQ_CMDxSND_LOGOFF
			<< (unsigned int)0x00
			<< dwUIN
			<< (unsigned int)0x00
			<< "B_USER_DISCONNECTED"
			<< (unsigned short)0x0005;

		Netlib_Logf(hNetlibUser, "[udp] logging off.\n");
		udpSocket.sendPacket(logoffPacket);
		//		udpSocket.closeConnection();

		// close all open events
		for (i = 0; i < icqEvents.size(); i++) delete icqEvents[i];
		icqEvents.clear();
	}

	statusVal = ID_STATUS_OFFLINE;

	if (reconnect) logon(desiredStatus);
	else {
		udpSocket.closeConnection();
		tcpSocket.closeConnection();

		updateContactList();
		ProtoBroadcastAck(protoName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)ID_STATUS_ONLINE, statusVal);
	}
}

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

void ICQ::ping()
{
	if (statusVal > ID_STATUS_OFFLINE) {
		Packet pingPacket;
		pingPacket << ICQ_VERSION
			<< ICQ_CMDxSND_PING
			<< sequenceVal
			<< (unsigned short)0x00
			<< dwUIN
			<< (unsigned int)0x00;

		Netlib_Logf(hNetlibUser, "[udp] keep alive (%d)\n", sequenceVal);
		sendICQ(udpSocket, pingPacket, ICQ_CMDxSND_PING, sequenceVal);
	}

	if (statusVal == ID_STATUS_OFFLINE && desiredStatus != ID_STATUS_OFFLINE) logoff(true);
}

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

ICQEvent *ICQ::sendICQ(Socket &socket, Packet &packet, unsigned short cmd, unsigned long sequence,
	unsigned long _uin, unsigned short subCmd, int reply)
{
	ICQEvent *result;

	if (!socket.connected())
		return nullptr;

	if (cmd != ICQ_CMDxTCP_START)
		sequenceVal++;

	icqEvents.push_back(result = new ICQEvent(cmd, subCmd, sequence, _uin, &socket, &packet, reply));
	if (!result->start()) {
		cancelEvent(result);
		return nullptr;
	}
	return result;
}

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

void ICQ::doneEvent(bool gotAck, int hSocket, int sequence)
{
	unsigned int i;
	ICQEvent *e = nullptr;

	for (i = 0; i < icqEvents.size(); i++) {
		e = icqEvents[i];
		if (e->isEvent(hSocket, sequence))
			break;
	}
	if (i == icqEvents.size())
		return;

	e->stop();
	if (!gotAck || e->reply == 0) {
		icqEvents[i] = icqEvents[icqEvents.size() - 1];
		icqEvents.pop_back();
	}

	if (!gotAck) Netlib_Logf(hNetlibUser, "[   ] sending failed (%d)\n", sequence);

	switch (e->cmd) {
	case ICQ_CMDxTCP_START:
		doneUserFcn(gotAck, e);
		break;
	case ICQ_CMDxSND_THRUxSERVER:
		doneUserFcn(gotAck, e);
		break;
	case ICQ_CMDxSND_USERxGETxINFO:
		//emit doneUserInfo(true, e->uin);
		break;
	case ICQ_CMDxSND_SETxSTATUS:
		if (gotAck) {
			int oldStatus = statusVal;
			statusVal = desiredStatus;
			ProtoBroadcastAck(protoName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)oldStatus, statusVal);
		}
		break;
	case ICQ_CMDxSND_PING:
		//if (!gotAck) emit doneOwnerFcn(false, cmd);
		break;
	case ICQ_CMDxSND_USERxADD:
		//if (!gotAck) emit doneOwnerFcn(false, cmd);
		break;
	case ICQ_CMDxSND_AUTHORIZE:
		//emit doneOwnerFcn(gotAck, cmd);
		break;
	case ICQ_CMDxSND_LOGON:
		if (!gotAck) {
			logoff(false);
			//emit doneOwnerFcn(false, cmd);
		}
		break;
	case ICQ_CMDxSND_USERxLIST:
		//if (!gotAck) emit doneOwnerFcn(false, cmd);
		break;
	case ICQ_CMDxSND_VISxLIST:
		//if (!gotAck) emit doneOwnerFcn(false, cmd);
		break;
	case ICQ_CMDxSND_SYSxMSGxREQ:
		//if (!gotAck) emit doneOwnerFcn(false, cmd);
		break;
	case ICQ_CMDxSND_SYSxMSGxDONExACK:
		//if (!gotAck) emit doneOwnerFcn(false, cmd);
		break;
	}

	if (!gotAck && e->cmd != ICQ_CMDxTCP_START && e->cmd != ICQ_CMDxSND_LOGON)
		logoff(true);

	if (!gotAck || e->reply == 0)
		delete e;
	else
		e->reply--;
}

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

void ICQ::cancelEvent(ICQEvent *&e)
{
	unsigned int i;

	for (i = 0; i < icqEvents.size(); i++) if (icqEvents[i] == e)
		break;
	if (i == icqEvents.size())
		return;

	e->stop();

	icqEvents[i] = icqEvents[icqEvents.size() - 1];
	icqEvents.pop_back();

	delete e;
	e = nullptr;
}

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

unsigned short ICQ::processUdpPacket(Packet &packet)
{
	unsigned short version, command, newCommand, theSequence, theSequence1, searchSequence, junkShort;
	unsigned int checkUin, userIP, realIP, junkl, newStatus, userPort, timedataStamp;
	unsigned char junkChar;
	char *message = nullptr;
	ICQUser *u;
	ICQEvent *e;

	// read in the standard UDP header info
	packet >> version
		>> command
		>> theSequence
		>> theSequence1
		>> checkUin
		>> junkl;

	if (version != ICQ_VERSION) {
		Netlib_Logf(hNetlibUser, "[udp] bad version number %d\n", version);
		return 0xFFFF;
	}

	switch (command) {
	case ICQ_CMDxRCV_LOGIN_ERR:
		Netlib_Logf(hNetlibUser, "[udp] error loging to server.\n");
		ackUDP(theSequence);

		packet >> message;

		Netlib_Logf(hNetlibUser, "%s\n", message);
		MessageBoxA(nullptr, message, protoName, MB_ICONERROR | MB_OK);
		delete[] message;
		break;

	case ICQ_CMDxRCV_USERxONLINE: // initial user status packet
		packet >> checkUin;

		Netlib_Logf(hNetlibUser, "[udp] user %d is online\n", checkUin);
		ackUDP(theSequence);

		if ((u = getUserByUIN(checkUin, false)) == nullptr) break;

		packet >> userIP
			>> userPort
			>> realIP
			>> junkChar
			>> newStatus;

		u->socket.closeConnection();
		u->socket.setDestination(userIP, userPort);
		u->setStatus(toIdStatus(newStatus));
		u->setInfo("IP", (unsigned int)ntohl(userIP));
		u->setInfo("Port", (unsigned short)userPort);
		u->setInfo("RealIP", (unsigned int)ntohl(realIP));
		break;

	case ICQ_CMDxRCV_USERxOFFLINE: // user just went offline packet
		packet >> checkUin;

		Netlib_Logf(hNetlibUser, "[udp] user %d is offline\n", checkUin);
		ackUDP(theSequence);

		if ((u = getUserByUIN(checkUin, false)) == nullptr) break;

		u->setStatus(ID_STATUS_OFFLINE);
		u->socket.closeConnection();
		break;

	case ICQ_CMDxRCV_USERxBASICxINFO:
	case ICQ_CMDxRCV_USERxINFO:
	case ICQ_CMDxRCV_USERxWORKxINFO:
	case ICQ_CMDxRCV_USERxWORKxPAGE:
	case ICQ_CMDxRCV_USERxHOMExINFO:
	case ICQ_CMDxRCV_USERxHOMExPAGE:
		Netlib_Logf(hNetlibUser, "[udp] user information packet (%d)\n", theSequence);
		ackUDP(theSequence);

		if ((e = getEvent(udpSocket.handleVal, theSequence1)) == nullptr) break;
		checkUin = e->uin;
		if ((u = getUserByUIN(checkUin, false)) == nullptr) break;

		char *buffer;
		buffer = new char[1024];

		switch (command) {
		case ICQ_CMDxRCV_USERxBASICxINFO:
		case ICQ_CMDxRCV_USERxINFO:
			packet >> buffer;
			u->setInfo("Nick", buffer);
			packet >> buffer;
			u->setInfo("FirstName", buffer);
			packet >> buffer;
			u->setInfo("LastName", buffer);
			packet >> buffer;
			u->setInfo("e-mail", buffer);
			break;

		case ICQ_CMDxRCV_USERxWORKxINFO:
			packet >> buffer;
			u->setInfo("CompanyStreet", buffer);
			packet >> buffer;
			u->setInfo("CompanyCity", buffer);
			packet >> buffer;
			u->setInfo("CompanyState", buffer);
			packet >> junkShort;
			u->setInfo("CompanyCountry", junkShort);
			packet >> buffer;
			u->setInfo("Company", buffer);
			packet >> buffer;
			u->setInfo("CompanyPosition", buffer);
			packet >> junkl;
			packet >> buffer;
			u->setInfo("CompanyPhone", buffer);
			packet >> buffer;
			u->setInfo("CompanyFax", buffer);
			packet >> buffer;
			packet >> junkl;
			if (junkl && junkl != 0xFFFFFFFF) _itoa(junkl, buffer, 10);
			else buffer[0] = 0;
			u->setInfo("CompanyZIP", buffer);
			break;

		case ICQ_CMDxRCV_USERxWORKxPAGE:
			packet >> buffer;
			u->setInfo("CompanyHomepage", buffer);
			break;

		case ICQ_CMDxRCV_USERxHOMExINFO:
			packet >> buffer;
			u->setInfo("Street", buffer);
			packet >> buffer;
			u->setInfo("City", buffer);
			packet >> buffer;
			u->setInfo("State", buffer);
			packet >> junkShort;
			u->setInfo("Country", junkShort);
			packet >> buffer;
			u->setInfo("Phone", buffer);
			packet >> buffer;
			u->setInfo("Fax", buffer);
			packet >> buffer;
			u->setInfo("Cellular", buffer);
			packet >> junkl;
			if (junkl && junkl != 0xFFFFFFFF) _itoa(junkl, buffer, 10);
			else buffer[0] = 0;
			u->setInfo("ZIP", buffer);
			packet >> junkChar;
			if (junkChar == 1) junkChar = 'F';
			if (junkChar == 2) junkChar = 'M';
			u->setInfo("Gender", junkChar);
			packet >> junkShort;
			u->setInfo("Age", (unsigned char)junkShort);
			packet >> junkChar;
			u->setInfo("BirthDay", junkChar);
			packet >> junkChar;
			u->setInfo("BirthMonth", junkChar);
			packet >> junkShort;
			u->setInfo("BirthYear", junkShort);
			break;

		case ICQ_CMDxRCV_USERxHOMExPAGE:
			packet >> buffer;
			u->setInfo("Homepage", buffer);
			break;
		}

		if (e->reply == 0)
			ProtoBroadcastAck(protoName, u->hContact, ACKTYPE_GETINFO, ACKRESULT_SUCCESS, nullptr, 0);
		doneEvent(true, udpSocket.handleVal, theSequence1);
		delete[] buffer;
		break;

	case ICQ_CMDxRCV_USERxINVALIDxUIN: // not a good uin
		Netlib_Logf(hNetlibUser, "[udp] invalid uin\n");
		ackUDP(theSequence);

		if ((e = getEvent(udpSocket.handleVal, theSequence1)) == nullptr) break;

		checkUin = e->uin;
		Netlib_Logf(hNetlibUser, "invalid uin: %d\n", checkUin);
		break;

	case ICQ_CMDxRCV_USERxSTATUS: // user changed status packet
		packet >> checkUin;

		Netlib_Logf(hNetlibUser, "[udp] user %d changed status\n", checkUin);
		ackUDP(theSequence);

		packet >> newStatus;

		if ((u = getUserByUIN(checkUin, false)) == nullptr) break;
		u->setStatus(toIdStatus(newStatus));
		break;

	case ICQ_CMDxRCV_USERxLISTxDONE: // end of user list
		Netlib_Logf(hNetlibUser, "[udp] end of user list.\n");
		ackUDP(theSequence);
		break;

	case ICQ_CMDxRCV_SEARCHxFOUND: // user found in search
		Netlib_Logf(hNetlibUser, "[udp] search found user\n");
		ackUDP(theSequence);

		char *alias, *firstName, *lastName, *email;
		unsigned char auth;

		alias = nullptr;
		firstName = nullptr;
		lastName = nullptr;
		email = nullptr;
		packet >> checkUin >> alias >> firstName >> lastName >> email >> auth;
		{
			ICQSEARCHRESULT psr = { 0 };
			psr.hdr.cbSize = sizeof(psr);
			psr.hdr.nick.a = alias;
			psr.hdr.firstName.a = firstName;
			psr.hdr.lastName.a = lastName;
			psr.hdr.email.a = email;
			psr.uin = checkUin;
			psr.auth = auth;
			ProtoBroadcastAck(protoName, NULL, ACKTYPE_SEARCH, ACKRESULT_DATA, (HANDLE)1, (LPARAM)&psr);
		}

		delete[] alias;
		delete[] firstName;
		delete[] lastName;
		delete[] email;
		break;

	case ICQ_CMDxRCV_SEARCHxDONE:
		Netlib_Logf(hNetlibUser, "[udp] search finished.\n");
		ackUDP(theSequence);

		packet >> searchSequence;
		searchSequence = theSequence1;

		ProtoBroadcastAck(protoName, NULL, ACKTYPE_SEARCH, ACKRESULT_SUCCESS, (HANDLE)1, 0);
		break;

	case ICQ_CMDxRCV_SYSxMSGxOFFLINE: // offline system message, now have to check the sub-command
		Netlib_Logf(hNetlibUser, "[udp] offline system message\n");
		ackUDP(theSequence);

		packet >> checkUin
			>> timedataStamp
			>> newCommand;

		timeStampLastMessage = timedataStamp;
		timedataStamp = TimeZone_ToLocal(timedataStamp);

		processSystemMessage(packet, checkUin, newCommand, timedataStamp);
		break;

	case ICQ_CMDxRCV_SYSxMSGxONLINE: // online system message, now have to check the sub-command
		Netlib_Logf(hNetlibUser, "[udp] online system message\n");
		ackUDP(theSequence);

		packet >> checkUin
			>> newCommand;

		processSystemMessage(packet, checkUin, newCommand, time(0));
		break;

	case ICQ_CMDxRCV_SYSxMSGxDONE: // end of system messages
		Netlib_Logf(hNetlibUser, "[udp] end of system messages.\n");
		ackUDP(theSequence);

		if (timeStampLastMessage) {
			ackSYS(timeStampLastMessage);
			timeStampLastMessage = 0;
		}
		break;

	case ICQ_CMDxRCV_BROADCASTxMULTI:
		Netlib_Logf(hNetlibUser, "[udp] broadcast multi-packet (%d)\n", theSequence);
		ackUDP(theSequence);

		unsigned int i;
		unsigned char j, frameNo, frameSize;
		bool found;

		packet >> frameNo
			>> frameSize;

		icqEvents.push_back(new ICQEvent(ICQ_CMDxRCV_BROADCASTxMULTI, (unsigned short)frameNo, theSequence1, 0, &udpSocket, &packet, 0));

		{
			Packet multiPacket;

			for (j = 0; j < frameSize; j++) {
				found = false;
				for (i = 0; i < icqEvents.size(); i++) {
					e = icqEvents[i];
					if (e->cmd == ICQ_CMDxRCV_BROADCASTxMULTI && e->subCmd == j && e->isEvent(udpSocket.handleVal, theSequence1)) {
						multiPacket << e->packet;
						found = true;
						break;
					}
				}
				if (!found)
					break;
			}

			if (j == frameSize) {
				for (i = 0; i < icqEvents.size(); i++) {
					e = icqEvents[i];
					if (e->cmd == ICQ_CMDxRCV_BROADCASTxMULTI && e->isEvent(udpSocket.handleVal, theSequence1)) {
						icqEvents[i] = icqEvents[icqEvents.size() - 1];
						icqEvents.pop_back();

						delete e;
					}
				}

				multiPacket.reset();
				processUdpPacket(multiPacket);
			}
		}
		break;

	case ICQ_CMDxRCV_BROADCASTxOFFLINE:
		Netlib_Logf(hNetlibUser, "[udp] offline broadcast message (%d)\n", theSequence);
		ackUDP(theSequence);

		packet >> checkUin
			>> timedataStamp
			>> newCommand;

		g_plugin.setDword("LastBroadcastTime", timedataStamp);
		timedataStamp = TimeZone_ToLocal(timedataStamp);

		processSystemMessage(packet, checkUin, newCommand, timedataStamp);
		break;

	case ICQ_CMDxRCV_BROADCASTxONLINE:
		Netlib_Logf(hNetlibUser, "[udp] online broadcast message (%d)\n", theSequence);
		ackUDP(theSequence);

		packet >> checkUin
			>> newCommand;

		processSystemMessage(packet, checkUin, newCommand, time(0));
		break;

	case ICQ_CMDxRCV_BROADCASTxDONE:
		Netlib_Logf(hNetlibUser, "[udp] end of broadcast messages.\n");
		ackUDP(theSequence);
		break;

	case ICQ_CMDxRCV_SETxOFFLINE: // we got put offline by mirabilis for some reason
		Netlib_Logf(hNetlibUser, "[udp] kicked offline.\n");
		logoff(true);
		break;

	case ICQ_CMDxRCV_ACK: // icq acknowledgement
		Netlib_Logf(hNetlibUser, "[udp] received ack (%d)\n", theSequence);
		doneEvent(true, udpSocket.handleVal, theSequence);
		break;

	case ICQ_CMDxRCV_ERROR: // icq says go away
		Netlib_Logf(hNetlibUser, "[udp] server says bugger off.\n");
		logoff(true);
		break;

	case ICQ_CMDxRCV_HELLO: // hello packet from mirabilis received on logon
		Netlib_Logf(hNetlibUser, "[udp] received hello.\n");
		ackUDP(theSequence);

		int oldStatus;

		requestSystemMsg();
		requestBroadcastMsg();

		//	pingTimer.start(PING_FREQUENCY * 1000);
		oldStatus = statusVal;
		statusVal = desiredStatus;
		ProtoBroadcastAck(protoName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)oldStatus, statusVal);

		updateContactList();
		// sendVisibleList();
		// sendInvisibleList();
		break;

	case ICQ_CMDxRCV_WRONGxPASSWD: // incorrect password sent in logon
		Netlib_Logf(hNetlibUser, "[udp] incorrect password.\n");
		ProtoBroadcastAck(protoName, NULL, ACKTYPE_LOGIN, ACKRESULT_FAILED, nullptr, LOGINERR_WRONGPASSWORD);
		MessageBox(nullptr, TranslateT("Your ICQ Corp number and password combination was rejected by the ICQ Corporate server. Please go to Options -> Network -> ICQCorp and try again."), _A2T(protoName), MB_ICONERROR | MB_OK);
		break;

	case ICQ_CMDxRCV_BUSY: // server too busy to respond
		Netlib_Logf(hNetlibUser, "[udp] server busy, try again in a few minutes.\n");
		break;

	default: // what the heck is this packet?
		Netlib_Logf(hNetlibUser, "[udp] unknown packet:\n%s", packet.print());
		ackUDP(theSequence);
		break;
	}

	return command;
}

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

void ICQ::processSystemMessage(Packet &packet, unsigned long checkUin, unsigned short newCommand, time_t timeSent)
{
	char *message/*, *sysMsg*/;
	ICQUser *u;
	unsigned int i, /*j,*/ messageLen;

	u = getUserByUIN(checkUin);

	message = nullptr;
	packet >> message;

	switch (newCommand) {
	case ICQ_CMDxRCV_SYSxMSG:
		Netlib_Logf(hNetlibUser, "message through server from %d\n", checkUin);
		addMessage(u, message, timeSent);
		break;

	case ICQ_CMDxRCV_SYSxBROADCAST:
		Netlib_Logf(hNetlibUser, "broadcast message from %d\n", checkUin);

		messageLen = (unsigned int)mir_strlen(message);
		for (i = 0; i < messageLen; i++)
			if (message[i] == -2) // 0xFE
				message[i] = '\n';

		addMessage(u, message, timeSent);
		break;
		/*
			case ICQ_CMDxRCV_SYSxAUTHxREQ:  // system message: authorisation request
			// 02 00 04 01 08 00 8F 76 20 00 06 00 41 00 41 70 6F 74 68 65 6F 73 69 73
			// FE 47 72 61 68 61 6D FE 52 6F 66 66 FE 67 72 6F 66 66 40 75 77 61 74 65
			// 72 6C 6F 6F 2E 63 61 FE 31 FE 50 6C 65 61 73 65 20 61 75 74 68 6F 72 69
			// 7A 65 20 6D 65 2E 00
			Netlib_Logf(hNetlibUser, "authorization request from %ld.\n", checkUin);
			packet >> messageLen;
			message = new char[messageLen + 1];
			for (i=0; i<=messageLen; i++)
			{
			packet >> message[i];
			if (message[i] == -2)
			message[i] = '\n';
			}

			sysMsg = new char[messageLen + 128];
			sprintf(sysMsg, "(%s) Authorization request from %ld:\n%s", sm.timeRec(), checkUin, message);
			icqOwner.addMessage(sysMsg, timeSent);
			sprintf(sysMsg, "Authorization request from %ld:\n%s", checkUin, message);
			addToSystemMessageHistory(sysMsg);
			playSound(soundSysMsg);
			delete sysMsg;
			delete message;
			break;

			case ICQ_CMDxRCV_SYSxAUTHxGRANTED: // system message: authorization granted

			outputWindow->wprintf("  (%s) Authorization granted from %ld.", sm.timeRec(), checkUin);
			packet >> messageLen;
			message = new char[messageLen + 1];
			for (i = 0; i <= messageLen; i++)
			{
			packet >> message[i];
			if (message[i] == -2) message[i] = '\n';
			}

			sysMsg = new char[messageLen + 128];
			sprintf(sysMsg, "(%s) Authorization granted from %ld:\n%s", sm.timeRec(), checkUin, message);
			icqOwner.addMessage(sysMsg, timeSent);
			sprintf(sysMsg, "Authorization granted from %ld:\n%s", checkUin, message);
			addToSystemMessageHistory(sysMsg);
			playSound(soundSysMsg);

			delete sysMsg;
			delete message;
			break;
			*/
			/*
				case ICQ_CMDxRCV_SYSxADDED:  // system message: added to a contact list
				outputWindow->wprintf("  %C(%s) user %C%ld%C added you to their contact list.", COLOR_RECEIVE, sm.timeRec(), COLOR_DATA, checkUin, COLOR_RECEIVE);
				sysMsg = new char[128];
				sprintf(sysMsg, "(%s) User %ld added you to their contact list.", sm.timeRec(), checkUin);
				icqOwner.addMessage(sysMsg, timeSent);
				sprintf(sysMsg, "User %ld added you to their contact list.", checkUin);
				addToSystemMessageHistory(sysMsg);
				delete sysMsg;
				playSound(soundSysMsg);
				*/
				/* there is a bunch of info about the given user in the packet but the read routine to get
				  at it is totally broken right now
				  int infoLen, j;
				  packet >> infoLen;

				  // declare all the strings we will need for reading in the user data
				  char *userInfo, *aliasField, *firstNameField, *lastNameField, *emailField;
				  userInfo =	   new char[infoLen];
				  aliasField =	 new char[infoLen];
				  firstNameField = new char[infoLen];
				  lastNameField =  new char[infoLen];
				  emailField =	 new char[infoLen];

				  // read in the user data from the packet
				  for (i = 0; i < infoLen; i++) packet >> userInfo[i];

				  // parse the user info string for the four fields
				  i = j = 0;
				  do { aliasField[j] = userInfo[i];	 i++; j++;} while (userInfo[i] != -2);
				  aliasField[j] = '\0'; j = 0;
				  do { firstNameField[j] = userInfo[i]; i++; j++;} while (userInfo[i] != -2);
				  firstNameField[j] = '\0';  j = 0;
				  do { lastNameField[j] = userInfo[i];  i++; j++;} while (userInfo[i] != -2);
				  lastNameField[j] = '\0';  j = 0;
				  do { emailField[j] = userInfo[i];	 i++; j++;} while (i < infoLen);
				  emailField[j] = '\0';

				  *outputWindow << "  " << aliasField << " (" << firstNameField << " " << lastNameField << "), " << emailField << ".";

				  delete userInfo; delete aliasField; delete firstNameField; delete lastNameField; delete emailField;
				  break;
				  */

	default:
		Netlib_Logf(hNetlibUser, "[udp] unknown system packet:\n%s", packet.print());
		break;
	}

	delete[] message;
}

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

void ICQ::ackUDP(unsigned short theSequence)
{
	Packet packet;
	packet << ICQ_VERSION
		<< ICQ_CMDxSND_ACK
		<< theSequence
		<< (unsigned short)0x00
		<< dwUIN
		<< (unsigned int)0x00;

	Netlib_Logf(hNetlibUser, "[udp] sending ack (%d)\n", theSequence);
	udpSocket.sendPacket(packet);
}

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

void ICQ::ackSYS(unsigned int timeStamp)
{
	Packet packet;
	packet << ICQ_VERSION
		<< ICQ_CMDxSND_SYSxMSGxDONExACK
		<< sequenceVal
		<< sequenceVal
		<< dwUIN
		<< (unsigned int)0x00
		<< timeStamp;

	Netlib_Logf(hNetlibUser, "[udp] sending system message ack (%d)\n", sequenceVal);
	sendICQ(udpSocket, packet, ICQ_CMDxSND_SYSxMSGxDONExACK, sequenceVal);
}

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

ICQUser *ICQ::getUserByUIN(unsigned long _uin, bool allowAdd)
{
	unsigned long i;
	ICQUser *u;

	for (i = 0; i < icqUsers.size(); i++) {
		u = icqUsers[i];
		if (u->dwUIN == _uin)
			return u;
	}

	if (allowAdd) {
		Netlib_Logf(hNetlibUser, "unknown user %d, adding them to your list\n", _uin);
		return addUser(_uin, false);
	}

	Netlib_Logf(hNetlibUser, "ICQ sent unknown user %d\n", _uin);
	return nullptr;
}

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

ICQUser *ICQ::getUserByContact(MCONTACT hContact)
{
	for (size_t i = 0; i < icqUsers.size(); i++) {
		ICQUser *u = icqUsers[i];
		if (u->hContact == hContact)
			return u;
	}
	return nullptr;
}

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

void ICQ::requestSystemMsg()
{
	// request offline system messages
	// 02 00 4C 04 02 00 50 A5 82 00

	Packet packet;
	packet << ICQ_VERSION
		<< ICQ_CMDxSND_SYSxMSGxREQ
		<< sequenceVal
		<< sequenceVal
		<< dwUIN
		<< (unsigned int)0x00;

	Netlib_Logf(hNetlibUser, "[udp] sending offline system messages request (%d)...\n", sequenceVal);
	sendICQ(udpSocket, packet, ICQ_CMDxSND_SYSxMSGxREQ, sequenceVal);
}

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

void ICQ::requestBroadcastMsg()
{
	unsigned int timeStamp = g_plugin.getDword("LastBroadcastTime", 0);

	Packet packet;
	packet << ICQ_VERSION
		<< ICQ_CMDxSND_BROADCASTxREQ
		<< sequenceVal
		<< sequenceVal
		<< dwUIN
		<< (unsigned int)0x00
		<< timeStamp
		<< (unsigned int)0x00;

	Netlib_Logf(hNetlibUser, "[udp] sending offline broadcast messages request (%d)...\n", sequenceVal);
	sendICQ(udpSocket, packet, ICQ_CMDxSND_SYSxMSGxREQ, sequenceVal);
}

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

bool ICQ::setStatus(unsigned short newStatus)
{
	if (!udpSocket.connected())
		return false;

	Packet packet;
	packet << ICQ_VERSION
		<< ICQ_CMDxSND_SETxSTATUS
		<< sequenceVal
		<< sequenceVal
		<< dwUIN
		<< (unsigned int)0x00
		<< toIcqStatus(newStatus);

	Netlib_Logf(hNetlibUser, "[udp] sending set status packet (%d)\n", sequenceVal);
	sendICQ(udpSocket, packet, ICQ_CMDxSND_SETxSTATUS, sequenceVal);

	desiredStatus = newStatus;
	return true;
}

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

void ICQ::updateContactList()
{
	char *proto;
	unsigned int i;
	int userCount;
	//HANDLE hContact;
	ICQUser *u;

	for (auto &hContact : Contacts()) {
		proto = GetContactProto(hContact);
		if (proto && !mir_strcmp(proto, protoName)) {
			if ((u = getUserByContact(hContact)) == nullptr) {
				u = new ICQUser();
				u->hContact = hContact;
				u->dwUIN = g_plugin.getDword(hContact, "UIN", 0);
				icqUsers.push_back(u);
			}
			if (statusVal <= ID_STATUS_OFFLINE)
				u->setStatus(ID_STATUS_OFFLINE);
			else
				u->statusVal = g_plugin.getWord(hContact, "Status", ID_STATUS_OFFLINE);
		}
	}

	if (statusVal <= ID_STATUS_OFFLINE)
		return;

	// create user info packet
	Packet userPacket;
	for (i = 0; i < icqUsers.size();) {
		userCount = (unsigned int)icqUsers.size() - i;
		if (userCount > 100)
			userCount = 100;

		userPacket.clearPacket();
		userPacket << ICQ_VERSION
			<< ICQ_CMDxSND_USERxLIST
			<< sequenceVal
			<< sequenceVal
			<< dwUIN
			<< (unsigned int)0x00
			<< (unsigned char)userCount;

		for (; userCount > 0; userCount--) userPacket << icqUsers[i++]->dwUIN;

		// send user info packet
		Netlib_Logf(hNetlibUser, "[udp] sending contact list (%d)...\n", sequenceVal);
		sendICQ(udpSocket, userPacket, ICQ_CMDxSND_USERxLIST, sequenceVal);
	}
}

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

void ICQ::sendVisibleList()
{
	/*
		unsigned int i, numUsers = 0;
		ICQUser *u;

		if (statusVal != ID_STATUS_INVISIBLE) return;

		Packet userPacket;
		userPacket << ICQ_VERSION
		<< ICQ_CMDxSND_VISxLIST
		<< sequenceVal
		<< sequenceVal
		<< uin
		<< (unsigned int)0x00;

		for (i=0; i<icqUsers.size(); i++)
		{
		u = icqUsers[i];
		if (u->statusVal != ID_STATUS_OFFLINE && g_plugin.getWord(u->hContact, "ApparentMode") == ID_STATUS_ONLINE)
		numUsers++;
		}

		if (numUsers == 0) return;
		userPacket << (char)numUsers;

		for (i=0; i<icqUsers.size(); i++)
		{
		u = icqUsers[i];
		if (u->statusVal != ID_STATUS_OFFLINE && g_plugin.getWord(u->hContact, "ApparentMode") == ID_STATUS_ONLINE)
		userPacket << icqUsers[i]->uin;
		}

		Netlib_Logf(hNetlibUser, "[udp] sending visible list (%d)\n", sequenceVal);
		sendICQ(udpSocket, userPacket, ICQ_CMDxSND_VISxLIST, sequenceVal);
		*/
}

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

void ICQ::sendInvisibleList()
{
	/*
		unsigned int i, numUsers = 0;

		Packet userPacket;
		userPacket << ICQ_VERSION
		<< ICQ_CMDxSND_INVISxLIST
		<< sequenceVal
		<< sequenceVal
		<< uin
		<< (unsigned int)0x00;

		for (i=0; i<icqUsers.size(); i++)
		{
		if (g_plugin.getWord(icqUsers[i]->hContact, "ApparentMode") == ID_STATUS_OFFLINE)
		numUsers++;
		}

		if (numUsers == 0) return;
		userPacket << (char)numUsers;

		for (i=0; i<icqUsers.size(); i++)
		{
		if (g_plugin.getWord(icqUsers[i]->hContact, "ApparentMode") == ID_STATUS_OFFLINE)
		userPacket << icqUsers[i]->uin;
		}

		Netlib_Logf(hNetlibUser, "[udp] sending invisible list (%d)\n", sequenceVal);
		sendICQ(udpSocket, userPacket, ICQ_CMDxSND_INVISxLIST, sequenceVal);
		*/
}

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

void ICQ::updateUserList(ICQUser* /*u*/, char /*list*/, char /*add*/)
{
	/*
		Packet userPacket;
		userPacket << ICQ_VERSION
		<< ICQ_CMDxSND_UPDATExLIST
		<< sequenceVal
		<< sequenceVal
		<< uin
		<< (unsigned int)0x00
		<< u->uin
		<< list
		<< add;

		Netlib_Logf(hNetlibUser, "[udp] update user list (%d)\n", sequenceVal);
		sendICQ(udpSocket, userPacket, ICQ_CMDxSND_UPDATExLIST, sequenceVal);
		*/
}

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

ICQUser* ICQ::addUser(unsigned int uin, bool persistent)
{
	unsigned int i;
	ICQUser *u;

	for (i = 0; i < icqUsers.size(); i++) {
		u = icqUsers[i];
		if (u->dwUIN == uin) {
			if (persistent) {
				db_unset(u->hContact, "CList", "NotOnList");
				Contact_Hide(u->hContact, false);
			}
			return u;
		}
	}

	u = new ICQUser();
	u->dwUIN = uin;
	u->hContact = db_add_contact();
	icqUsers.push_back(u);

	Proto_AddToContact(u->hContact, protoName);
	u->setInfo("UIN", uin);

	if (persistent)
		getUserInfo(u, true);
	else {
		db_set_b(u->hContact, "CList", "NotOnList", 1);
		Contact_Hide(u->hContact);
	}

	updateContactList();
	return u;
}

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

void ICQ::addNewUser(ICQUser*)
{
	/*
		// update the users info from the server
		if (statusVal != ICQ_STATUS_OFFLINE)
		{
		Packet packet;  // alert server to new user

		packet << ICQ_VERSION
		<< ICQ_CMDxSND_USERxADD
		<< sequenceVal
		<< sequenceVal
		<< uin
		<< (unsigned int)0x00
		<< u->uin;

		Netlib_Logf(hNetlibUser, "[udp] alerting server to new user (%d)...\n", sequenceVal);
		sendICQ(udpSocket, packet, ICQ_CMDxSND_USERxADD, sequenceVal);

		//	  getUserInfo(u);
		}
		*/
	updateContactList();
}

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

void ICQ::removeUser(ICQUser *u)
{
	unsigned int i;

	for (i = 0; i < icqUsers.size(); i++) if (icqUsers[i] == u) break;
	if (i == icqUsers.size()) return;

	icqUsers[i] = icqUsers[icqUsers.size() - 1];
	icqUsers.pop_back();

	delete u;
}

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

void ICQ::startSearch(unsigned char skrit, unsigned char smode, char *sstring, unsigned int s)
{
	Packet packet;
	packet << ICQ_VERSION
		<< ICQ_CMDxSND_SEARCHxSTART
		<< sequenceVal
		<< (unsigned short)s
		//		   << (unsigned short)(icqOwner.sequence1())
		<< dwUIN
		<< (unsigned int)0x00
		<< (unsigned char)0xFF
		<< skrit
		<< (unsigned char)0x00
		<< smode
		<< sstring;

	Netlib_Logf(hNetlibUser, "[udp] starting search for user (%d)...\n", s);
	sendICQ(udpSocket, packet, ICQ_CMDxSND_SEARCHxSTART, sequenceVal);
}

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

ICQEvent *ICQ::send(ICQUser *u, unsigned short cmd, char *cmdStr, char *m)
{
	ICQEvent *result;

	if (u->statusVal > ID_STATUS_OFFLINE && (result = sendTCP(u, cmd, cmdStr, m)) != nullptr) return result;
	else return sendUDP(u, cmd, cmdStr, m);
}

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

bool ICQ::openConnection(TCPSocket &socket)
{
	Netlib_Logf(hNetlibUser, "[tcp] connecting to %s on port %d...\n", inet_ntoa(*(in_addr*)&socket.remoteIPVal), socket.remotePortVal);
	socket.openConnection();

	if (!socket.connected()) {
		Netlib_Logf(hNetlibUser, "[tcp] connect failed\n");
		return false;
	}

	Netlib_Logf(hNetlibUser, "[tcp] connection successful\n");

	Packet packet;
	//	packet << ICQ_CMDxTCP_HANDSHAKE3
	packet << (unsigned char)0xFF
		<< (unsigned int)0x02
		<< (unsigned int)0x00
		//		   << (unsigned long)tcpSocket.localPortVal
		<< dwUIN
		<< socket.localIPVal
		<< socket.localIPVal
		<< (unsigned char)0x04
		<< (unsigned int)0x00;
	//		   << (unsigned long)tcpSocket.localPortVal;

	Netlib_Logf(hNetlibUser, "[tcp] sending handshake\n");
	if (!socket.sendPacket(packet)) {
		Netlib_Logf(hNetlibUser, "[tcp] send failed\n");
		return false;
	}

	Netlib_Logf(hNetlibUser, "[tcp] setup completed\n");
	return true;
}

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

ICQEvent *ICQ::sendTCP(ICQUser *u, unsigned short cmd, char *cmdStr, char *m)
{
	if (!u->socket.connected() && !openConnection(u->socket))
		return nullptr;

	unsigned int status;
	switch (statusVal) {
	case ID_STATUS_ONLINE: status = 0x00100000; break;
	case ID_STATUS_FREECHAT: status = 0x00000000; break;  // ??
	case ID_STATUS_AWAY: status = 0x01100000; break;
	case ID_STATUS_NA: status = 0x00100000; break;
	case ID_STATUS_DND: status = 0x00100000; break;
	case ID_STATUS_OCCUPIED: status = 0x02100000; break;
	case ID_STATUS_INVISIBLE: status = 0x00900000; break;	  // ??
	default: status = 0x00100000; break;
	}

	Packet packet;
	packet << dwUIN
		<< (unsigned short)0x02			// ICQ_VERSION
		<< ICQ_CMDxTCP_START				 // ICQ_CMDxTCP_ACK, ICQ_CMDxTCP_START, ICQ_CMDxTCP_CANCEL
		<< (unsigned short)0x00
		<< dwUIN
		<< cmd
		<< m
		<< udpSocket.localIPVal
		<< udpSocket.localIPVal
		<< tcpSocket.localPortVal
		<< (unsigned char)0x04
		<< status
		<< tcpSequenceVal--;

	Netlib_Logf(hNetlibUser, "[tcp] sending %s (%d)\n", cmdStr, tcpSequenceVal + 1);
	return sendICQ(u->socket, packet, ICQ_CMDxTCP_START, tcpSequenceVal + 1, u->dwUIN, cmd);
}

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

ICQEvent *ICQ::sendUDP(ICQUser *u, unsigned short cmd, char *cmdStr, char *m)
{
	Packet packet;
	packet << ICQ_VERSION
		<< ICQ_CMDxSND_THRUxSERVER
		<< sequenceVal
		<< sequenceVal
		<< dwUIN
		<< (unsigned int)0x00
		<< u->dwUIN
		<< cmd
		<< m;

	/*  write for offline multi packet, but not work - little architecturial trouble:
		one big packet must divided on several little packets and Miranda use returned ONE event for control process sending,
		but not several events

		if (packet.size() > 450)
		{
		unsigned int i, j = 0;
		unsigned char c, frameNo, frameSize;

		packet.reset();

		frameSize = (packet.size()+449) / 450;
		for (frameNo=0; frameNo<frameSize; frameNo++)
		{
		Packet frame;
		frame << ICQ_VERSION
		<< ICQ_CMDxSND_MULTI
		<< sequenceVal
		<< sequenceVal
		<< uin
		<< (unsigned int)0x00
		<< frameSize
		<< frameNo;

		for (i=0; i<450 && j<packet.size(); i++, j++)
		{
		packet >> c;
		frame << c;
		}

		Netlib_Logf(hNetlibUser, "[udp] sending %s through server, part %d of %d (%d)\n", cmdStr, frameNo, frameSize, sequenceVal);
		sendICQ(udpSocket, packet, ICQ_CMDxSND_THRUxSERVER, sequenceVal, u->uin, cmd);
		}
		}
		else
		*/
	{
		Netlib_Logf(hNetlibUser, "[udp] sending %s through server (%d)\n", cmdStr, sequenceVal);
		return sendICQ(udpSocket, packet, ICQ_CMDxSND_THRUxSERVER, sequenceVal, u->dwUIN, cmd);
	}
}

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

ICQEvent *ICQ::sendMessage(ICQUser *u, char *m)
{
	return send(u, ICQ_CMDxTCP_MSG, "message", m);
}

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

ICQEvent *ICQ::sendUrl(ICQUser *u, char *url)
{
	unsigned int nameLen, descriptionLen;
	char *m, *description;
	ICQEvent *result;

	nameLen = (unsigned int)mir_strlen(url);
	description = (char*)url + nameLen + 1;
	descriptionLen = (unsigned int)mir_strlen(description);

	m = new char[nameLen + descriptionLen + 2];
	mir_strcpy(m, description);
	mir_strcpy(m + descriptionLen + 1, url);
	m[descriptionLen] = -2; // 0xFE;

	result = send(u, ICQ_CMDxTCP_URL, "url", m);
	delete[] m;

	return result;
}

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

ICQEvent *ICQ::sendReadAwayMsg(ICQUser *u)
{
	unsigned short cmd;

	switch (u->statusVal) {
	case ID_STATUS_AWAY: cmd = ICQ_CMDxTCP_READxAWAYxMSG; break;
	case ID_STATUS_DND: cmd = ICQ_CMDxTCP_READxDNDxMSG; break;
	case ID_STATUS_NA: cmd = ICQ_CMDxTCP_READxNAxMSG; break;
	case ID_STATUS_OCCUPIED: cmd = ICQ_CMDxTCP_READxOCCUPIEDxMSG; break;
	case ID_STATUS_FREECHAT: cmd = ICQ_CMDxTCP_READxFREECHATxMSG; break;
	default: return nullptr;
	}

	return sendTCP(u, cmd, "away message request", "");
}

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

ICQTransfer *ICQ::sendFile(ICQUser *u, char *description, char *filename, unsigned int size, wchar_t **files)
{
	if (!u->socket.connected() && !openConnection(u->socket))
		return nullptr;

	ICQTransfer *transfer = new ICQTransfer(u, tcpSequenceVal);

	int i;
	for (i = 0; files[i]; i++);
	transfer->files = new wchar_t*[i + 1];
	for (i = 0; files[i]; i++)
		transfer->files[i] = _wcsdup(files[i]);
	transfer->files[i] = nullptr;

	transfer->description = _strdup(description);
	transfer->count = i;
	transfer->totalSize = size;

	transfer->path = _wcsdup(transfer->files[0]);
	wchar_t *s = wcsrchr(transfer->path, '\\');
	if (s != nullptr)
		*s = 0;

	icqTransfers.push_back(transfer);
	transfer->ack(ACKRESULT_SENTREQUEST);

	unsigned short cmd = ICQ_CMDxTCP_FILE;
	char *m = description;

	unsigned int status;
	switch (statusVal) {
	case ID_STATUS_ONLINE: status = 0x00100000; break;
	case ID_STATUS_FREECHAT: status = 0x00000000; break;  // ??
	case ID_STATUS_AWAY: status = 0x01100000; break;
	case ID_STATUS_NA: status = 0x00100000; break;
	case ID_STATUS_DND: status = 0x00100000; break;
	case ID_STATUS_OCCUPIED: status = 0x02100000; break;
	case ID_STATUS_INVISIBLE: status = 0x00900000; break;	  // ??
	default: status = 0x00100000; break;
	}

	Packet packet;
	packet << dwUIN
		<< (unsigned short)0x02			// ICQ_VERSION
		<< ICQ_CMDxTCP_START				 // ICQ_CMDxTCP_ACK, ICQ_CMDxTCP_START, ICQ_CMDxTCP_CANCEL
		<< (unsigned short)0x00
		<< dwUIN
		<< cmd
		<< m
		<< udpSocket.localIPVal
		<< udpSocket.localIPVal
		<< tcpSocket.localPortVal
		<< (unsigned char)0x04
		<< status;


	packet << (unsigned int)0x00
		<< filename
		<< size
		<< (unsigned int)0x00;

	packet << tcpSequenceVal--;

	Netlib_Logf(hNetlibUser, "[tcp] sending file request (%d)\n", tcpSequenceVal + 1);
	sendICQ(u->socket, packet, ICQ_CMDxTCP_START, tcpSequenceVal + 1, u->dwUIN, cmd);
	return transfer;
}

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

void ICQ::acceptFile(ICQUser *u, unsigned long hTransfer, char*)
{
	unsigned int theSequence = hTransfer;
	unsigned short cmd = ICQ_CMDxTCP_FILE;
	char m[1] = { 0 };

	unsigned long status;
	switch (statusVal) {
	case ID_STATUS_ONLINE: status = 0x00100000; break;
	case ID_STATUS_FREECHAT: status = 0x00000000; break;  // ??
	case ID_STATUS_AWAY: status = 0x01100000; break;
	case ID_STATUS_NA: status = 0x00100000; break;
	case ID_STATUS_DND: status = 0x00100000; break;
	case ID_STATUS_OCCUPIED: status = 0x02100000; break;
	case ID_STATUS_INVISIBLE: status = 0x00900000; break;	  // ??
	default: status = 0x00100000; break;
	}

	Packet packet;
	packet << dwUIN
		<< (unsigned short)0x02			// ICQ_VERSION
		<< ICQ_CMDxTCP_ACK				 // ICQ_CMDxTCP_ACK, ICQ_CMDxTCP_START, ICQ_CMDxTCP_CANCEL
		<< (unsigned short)0x00
		<< dwUIN
		<< cmd
		<< m
		<< udpSocket.localIPVal
		<< udpSocket.localIPVal
		<< tcpSocket.localPortVal
		<< (unsigned char)0x04
		<< (unsigned int)0x00;

	packet << (unsigned int)htons(tcpSocket.localPortVal)
		<< m
		<< (unsigned int)0x00
		<< tcpSocket.localPortVal;

	packet << theSequence;

	Netlib_Logf(hNetlibUser, "[tcp] sending accept file ack (%d)\n", theSequence);
	u->socket.sendPacket(packet);
}

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

void ICQ::refuseFile(ICQUser *u, unsigned long hTransfer, char *reason)
{
	unsigned int theSequence = hTransfer;
	unsigned short cmd = ICQ_CMDxTCP_FILE;
	char m[1] = { 0 };

	unsigned int status;
	switch (statusVal) {
	case ID_STATUS_ONLINE: status = 0x00100000; break;
	case ID_STATUS_FREECHAT: status = 0x00000000; break;  // ??
	case ID_STATUS_AWAY: status = 0x01100000; break;
	case ID_STATUS_NA: status = 0x00100000; break;
	case ID_STATUS_DND: status = 0x00100000; break;
	case ID_STATUS_OCCUPIED: status = 0x02100000; break;
	case ID_STATUS_INVISIBLE: status = 0x00900000; break;	  // ??
	default: status = 0x00100000; break;
	}

	Packet packet;
	packet << dwUIN
		<< (unsigned short)0x02			// ICQ_VERSION
		<< ICQ_CMDxTCP_ACK				   // ICQ_CMDxTCP_ACK, ICQ_CMDxTCP_START, ICQ_CMDxTCP_CANCEL
		<< (unsigned short)0x00
		<< dwUIN
		<< cmd
		<< reason
		<< udpSocket.localIPVal
		<< udpSocket.localIPVal
		<< tcpSocket.localPortVal
		<< (unsigned char)0x04
		<< (unsigned int)0x00000001;

	packet << (unsigned int)0x00
		<< m
		<< (unsigned int)0x00
		<< (unsigned int)0x00;

	packet << theSequence;

	Netlib_Logf(hNetlibUser, "[tcp] sending refuse file ack (%d)\n", theSequence);
	u->socket.sendPacket(packet);
}

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

bool ICQ::getUserInfo(ICQUser *u, bool basicInfo)
{
	unsigned short cmd = basicInfo ? ICQ_CMDxSND_USERxGETxBASICxINFO : ICQ_CMDxSND_USERxGETxINFO;

	Packet request;
	request << ICQ_VERSION
		<< cmd
		<< sequenceVal
		<< sequenceVal
		<< dwUIN
		<< (unsigned int)0x00
		<< u->dwUIN;

	Netlib_Logf(hNetlibUser, "[udp] sending user %s info request (%d)...\n", basicInfo ? "basic" : "details", sequenceVal);
	sendICQ(udpSocket, request, cmd, sequenceVal, u->dwUIN, 0, basicInfo ? 1 : 5);
	return true;
}

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

void ICQ::authorize(unsigned int uinToAuthorize)
{
	Packet packet;
	packet << ICQ_VERSION
		<< ICQ_CMDxSND_AUTHORIZE
		<< sequenceVal
		<< sequenceVal
		<< dwUIN
		<< (unsigned int)0x00
		<< uinToAuthorize
		<< (unsigned int)0x00010008   // who knows, seems to be constant
		<< (unsigned char)0x00;

	Netlib_Logf(hNetlibUser, "[udp] sending authorization (%d)\n", sequenceVal);
	sendICQ(udpSocket, packet, ICQ_CMDxSND_AUTHORIZE, sequenceVal);
}

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

void ICQ::processTcpPacket(Packet &packet, unsigned int hSocket)
{
	unsigned int i, checkUin, senderIp, localIp, userStatus, senderPort, junkLong, thePort, theTCPSequence = 0;
	unsigned short version, command, junkShort, newCommand, /*messageLen,*/ cicqVersion;
	unsigned char cicqChar, junkChar;
	char *message = nullptr;
	ICQUser *u;
	static unsigned int chatUin, chatSequence;

	packet >> checkUin
		>> version
		>> command	  // so far either message stuff or message ack
		>> junkShort	// 00 00 to fill in the MSB of the command long int which is read in as a short
		>> checkUin
		>> newCommand   // if a message then what type, message/chat/read away message/...
		>> message
		>> senderIp
		>> localIp
		>> senderPort
		>> junkChar
		>> userStatus;

	u = getUserByUIN(checkUin);
	switch (command) {
	case ICQ_CMDxTCP_START: // incoming tcp packet containing one of many possible things
		switch (newCommand) { // do a switch on what it could be
		case ICQ_CMDxTCP_MSG:  // straight message from a user
			Netlib_Logf(hNetlibUser, "[tcp] message from %d.\n", checkUin);

			packet >> theTCPSequence;

			ackTCP(packet, u, newCommand, theTCPSequence);
			addMessage(u, message, time(0));
			break;

		case ICQ_CMDxTCP_CHAT:
			Netlib_Logf(hNetlibUser, "[tcp] chat request from %d.\n", checkUin);

			packet >> junkLong
				>> junkLong
				>> junkShort
				>> junkChar
				>> theTCPSequence
				>> cicqChar
				>> cicqVersion;
			break;

		case ICQ_CMDxTCP_FILE:
			unsigned int size;
			char *fileName;

			fileName = nullptr;
			packet >> junkLong
				>> fileName
				>> size
				>> junkLong
				>> theTCPSequence;

			Netlib_Logf(hNetlibUser, "[tcp] file transfer request from %d (%d)\n", checkUin, theTCPSequence);

			addFileReq(u, message, fileName, size, theTCPSequence, time(0));
			delete[] fileName;
			break;

		case ICQ_CMDxTCP_READxAWAYxMSG: // read away message
		case ICQ_CMDxTCP_READxOCCUPIEDxMSG:
		case ICQ_CMDxTCP_READxNAxMSG:
		case ICQ_CMDxTCP_READxDNDxMSG:
		case ICQ_CMDxTCP_READxFREECHATxMSG:
			Netlib_Logf(hNetlibUser, "[tcp] %d requested read of away message.\n", checkUin);

			packet >> theTCPSequence;
			ackTCP(packet, u, newCommand, theTCPSequence);
			break;
		}
		break;

	case ICQ_CMDxTCP_ACK:  // message received packet
		switch (newCommand) {
		case ICQ_CMDxTCP_MSG:
			packet >> theTCPSequence;
			break;

		case ICQ_CMDxTCP_CHAT:
			packet >> junkShort
				>> junkChar
				>> junkLong   // port backwards
				>> thePort	// port to connect to for chat
				>> theTCPSequence;

			if (chatSequence != theTCPSequence || chatUin != checkUin) { // only if this is the first chat ack packet
				chatSequence = theTCPSequence;
				chatUin = checkUin;
				// emit eventResult(u, ICQ_CMDxTCP_CHAT, userStatus == 0x0000 ? true : false, thePort);
			}
			break;

		case ICQ_CMDxTCP_URL:
			packet >> theTCPSequence;
			break;

		case ICQ_CMDxTCP_FILE:
			packet >> junkLong
				>> junkShort
				>> junkChar
				>> junkLong
				>> thePort
				>> theTCPSequence;

			Netlib_Logf(hNetlibUser, "[tcp] file transfer ack from %d (%d)\n", u->dwUIN, theTCPSequence);

			ICQTransfer *t;
			for (i = 0; i < icqTransfers.size(); i++) {
				t = icqTransfers[i];
				if (t->uin == checkUin && !t->socket.connected()) {
					if (userStatus != 0) {
						Netlib_Logf(hNetlibUser, "[tcp] file transfer denied by %d\n", checkUin);
						ProtoBroadcastAck(protoName, t->hContact, ACKTYPE_FILE, ACKRESULT_DENIED, t, 0);
						delete t;
						icqTransfers[i] = icqTransfers[icqTransfers.size() - 1];
						icqTransfers.pop_back();
						break;
					}

					if (!t->socket.setDestination(u->socket.remoteIPVal, thePort)) {
						Netlib_Logf(hNetlibUser, "[tcp] can't set destination\n");
						break;
					}
					t->ack(ACKRESULT_CONNECTING);
					if (openConnection(t->socket)) {
						t->ack(ACKRESULT_CONNECTED);
						t->sendPacket0x00();
					}
					break;
				}
			}
			break;

		case ICQ_CMDxTCP_READxAWAYxMSG:
		case ICQ_CMDxTCP_READxOCCUPIEDxMSG:
		case ICQ_CMDxTCP_READxNAxMSG:
		case ICQ_CMDxTCP_READxDNDxMSG:
		case ICQ_CMDxTCP_READxFREECHATxMSG:
			packet >> theTCPSequence;
			addAwayMsg(u, message, theTCPSequence, time(0));
			break;
		}

		// output the away message if there is one (ie if user status is not online)
		if (userStatus == 0x0000)
			Netlib_Logf(hNetlibUser, "[tcp] ack from %d (%d).\n", u->dwUIN, theTCPSequence);
		else if (userStatus == 0x0001)
			Netlib_Logf(hNetlibUser, "[tcp] refusal from %d (%d): %s\n", u->dwUIN, theTCPSequence, message);
		else {
			// u->setAwayMessage(message);
			Netlib_Logf(hNetlibUser, "[tcp] ack from %d (%d).\n", u->dwUIN, theTCPSequence);
			// Netlib_Logf(hNetlibUser, "[tcp] ack from %d (%ld): %s\n", u->uin, theTCPSequence, message);
		}

		doneEvent(true, hSocket, theTCPSequence);
		break;

	case ICQ_CMDxTCP_CANCEL:
		switch (newCommand) {
		case ICQ_CMDxTCP_CHAT:
			Netlib_Logf(hNetlibUser, "[tcp] chat request from %d (%d) cancelled.\n", checkUin, theTCPSequence);
			// u->addMessage(chatReq, 0);
			break;

		case ICQ_CMDxTCP_FILE:
			Netlib_Logf(hNetlibUser, "[tcp] file transfer request from %d (%d) cancelled.\n", u->dwUIN, theTCPSequence);
			// u->addMessage(fileReq, 0);
			break;
		}
		break;

	default:
		Netlib_Logf(hNetlibUser, "[tcp] unknown packet:\n%s", packet.print());
		packet.reset();
	}
	delete[] message;
}

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

void ICQ::ackTCP(Packet &packet, ICQUser *u, unsigned short newCommand, unsigned int theSequence)
{
	unsigned int status;

	switch (statusVal) {
	case ID_STATUS_ONLINE: status = 0x00100000; break;
	case ID_STATUS_FREECHAT: status = 0x00000000; break;	// ??
	case ID_STATUS_AWAY: status = 0x01100000; break;
	case ID_STATUS_NA: status = 0x00100000; break;
	case ID_STATUS_DND: status = 0x00100000; break;
	case ID_STATUS_OCCUPIED: status = 0x02100000; break;
	case ID_STATUS_INVISIBLE: status = 0x00900000; break;   // ??
	default: status = 0x00100000; break;
	}

	packet.clearPacket();
	packet << dwUIN
		<< (unsigned short)0x02
		<< (unsigned short)ICQ_CMDxTCP_ACK // ICQ_CMDxTCP_ACK, ICQ_CMDxTCP_START, ICQ_CMDxTCP_CANCEL
		<< (unsigned short)0x00
		<< dwUIN
		<< newCommand
		<< awayMessage
		<< u->socket.localIPVal
		<< u->socket.localIPVal
		<< u->socket.localPortVal
		<< (unsigned char)0x04
		<< status
		<< theSequence;

	Netlib_Logf(hNetlibUser, "[tcp] sending ack (%d)\n", theSequence);
	u->socket.sendPacket(packet);
}

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

void ICQ::recvUDP(int)
{
	Packet packet;

	// mirabilis contacts us using udp on this server
	if (udpSocket.receivePacket(packet)) processUdpPacket(packet);
}

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

void ICQ::recvNewTCP(int)
{
	ICQUser *u;
	Packet handshake;

	// our tcp incoming server
	TCPSocket newSocket(0);
	tcpSocket.receiveConnection(newSocket);
	newSocket.receivePacket(handshake);

	unsigned int ulJunk, newUin, localHost;
	unsigned short command, usJunk;
	unsigned char ucJunk;

	handshake >> command;

	if (command != ICQ_CMDxTCP_HANDSHAKE && command != ICQ_CMDxTCP_HANDSHAKE2 && command != ICQ_CMDxTCP_HANDSHAKE3) {
		Netlib_Logf(hNetlibUser, "[tcp] garbage packet:\n%s", handshake.print());
		handshake.reset();
	}
	else {
		handshake >> ulJunk
			>> usJunk
			>> ucJunk
			>> newUin
			>> localHost
			>> localHost
			>> ulJunk
			>> ucJunk;

		u = getUserByUIN(newUin);
		if (!u->socket.connected()) {
			Netlib_Logf(hNetlibUser, "[tcp] connection from uin %d.\n", newUin);
			u->socket.transferConnectionFrom(newSocket);
		}
		else {
			unsigned int i;
			ICQTransfer *t;

			Netlib_Logf(hNetlibUser, "[tcp] file direct connection from uin %d.\n", newUin);
			for (i = 0; i < icqTransfers.size(); i++) {
				t = icqTransfers[i];
				if (t->uin == newUin && !t->socket.connected())
					t->socket.transferConnectionFrom(newSocket);
			}
		}
	}
}

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

void ICQ::recvTCP(SOCKET hSocket)
{
	for (size_t i = 0; i < icqUsers.size(); i++) {
		ICQUser *u = icqUsers[i];
		if (u->socket.handleVal == hSocket) {
			Packet packet;
			if (!u->socket.receivePacket(packet)) {
				Netlib_Logf(hNetlibUser, "[tcp] connection to %d lost.\n", u->dwUIN);
				return;
			}
			processTcpPacket(packet, hSocket);
			return;
		}
	}
}

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

void ICQ::recvTransferTCP(SOCKET hSocket)
{
	for (size_t i = 0; i < icqTransfers.size(); i++) {
		ICQTransfer *transfer = icqTransfers[i];
		if (transfer->socket.handleVal == hSocket) {
			Packet packet;
			if (!transfer->socket.receivePacket(packet)) {
				// Netlib_Logf(hNetlibUser, "[tcp] connection to %d lost.\n", s->uin);
				return;
			}
			transfer->processTcpPacket(packet);
			return;
		}
	}
}

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

void ICQ::addMessage(ICQUser *u, char *m, time_t t)
{
	Netlib_Logf(hNetlibUser, "message: %s\n", m);

	PROTORECVEVENT pre;
	pre.flags = 0;
	pre.timestamp = t;
	pre.szMessage = (char*)m;
	pre.lParam = 0;

	CCSDATA ccs;
	ccs.hContact = u->hContact;
	ccs.szProtoService = PSR_MESSAGE;
	ccs.wParam = 0;
	ccs.lParam = (LPARAM)&pre;
	Proto_ChainRecv(0, &ccs);
}

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

void ICQ::addAwayMsg(ICQUser *u, char *m, unsigned long theSequence, time_t t)
{
	Netlib_Logf(hNetlibUser, "away msg: %s\n", m);

	PROTORECVEVENT pre;
	pre.flags = 0;
	pre.timestamp = t;
	pre.szMessage = (char*)m;
	pre.lParam = theSequence;

	CCSDATA ccs;
	ccs.hContact = u->hContact;
	ccs.szProtoService = PSR_AWAYMSG;
	ccs.wParam = u->statusVal;
	ccs.lParam = (LPARAM)&pre;
	Proto_ChainRecv(0, &ccs);
}

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

void ICQ::addFileReq(ICQUser *u, char *m, char *filename, unsigned long size, unsigned long theSequence, time_t t)
{
	ICQTransfer *transfer = new ICQTransfer(u, theSequence);
	transfer->description = _strdup(m);
	transfer->totalSize = size;

	icqTransfers.push_back(transfer);

	// Send chain event
	char *szBlob = new char[sizeof(DWORD) + mir_strlen(filename) + mir_strlen(m) + 2];

	*(PDWORD)szBlob = (UINT_PTR)transfer;
	mir_strcpy(szBlob + sizeof(DWORD), filename);
	mir_strcpy(szBlob + sizeof(DWORD) + mir_strlen(filename) + 1, m);

	PROTORECVEVENT pre;
	pre.flags = 0;
	pre.timestamp = t;
	pre.szMessage = szBlob;
	pre.lParam = theSequence;

	CCSDATA ccs;
	ccs.hContact = u->hContact;
	ccs.szProtoService = PSR_FILE;
	ccs.wParam = 0;
	ccs.lParam = (LPARAM)&pre;
	Proto_ChainRecv(0, &ccs);

	delete[] szBlob;
}

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

void ICQ::doneUserFcn(bool ack, ICQEvent *icqEvent)
{
	unsigned int type = 0;

	if (icqEvent->subCmd == ICQ_CMDxTCP_MSG)
		type = ACKTYPE_MESSAGE;

	ProtoBroadcastAck(protoName, getUserByUIN(icqEvent->uin)->hContact, type, ack ? ACKRESULT_SUCCESS : ACKRESULT_FAILED, (HANDLE)icqEvent->sequence, 0);
}